source
stringlengths
3
92
c
stringlengths
26
2.25M
omp_task_firstprivate.c
<ompts:test> <ompts:testdescription>Test which checks the firstprivate clause of the task directive. We create a set of tasks in a single region. We defines a variable named sum unequal zero which gets declared firstprivate for each task. Now each task calcualtes a sum using this private variable. Before each calcualation step we introduce a flush command so that maybe the private variabel gets bad. At the end we check if the calculated sum was right.</ompts:testdescription> <ompts:ompversion>3.0</ompts:ompversion> <ompts:directive>omp task firstprivate</ompts:directive> <ompts:dependences>omp single,omp flush,omp critical</ompts:dependences> <ompts:testcode> #include <stdio.h> #include <math.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_task_firstprivate</ompts:testcode:functionname> (FILE * logFile) { int i; <ompts:orphan:vars> int sum = 1234; int known_sum; int result = 0; /* counts the wrong sums from tasks */ </ompts:orphan:vars> known_sum = 1234 + (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; #pragma omp parallel { #pragma omp single { for (i = 0; i < NUM_TASKS; i++) { <ompts:orphan> #pragma omp task <ompts:check>firstprivate(sum)</ompts:check> { int j; for (j = 0; j <= LOOPCOUNT; j++) { #pragma omp flush sum += j; } /* check if calculated sum was right */ if (sum != known_sum) { #pragma omp critical { result++; } } } /* end of omp task */ </ompts:orphan> } /* end of for */ } /* end of single */ } /* end of parallel*/ return (result == 0); } </ompts:testcode> </ompts:test>
alignment.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 */ /**********************************************************************************************/ /* Original code from the Application Kernel Matrix by Cray */ /* that was based on the ClustalW application */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <libgen.h> #include "sequence.h" #include "param.h" #include "alignment.h" #include "bots.h" int ktup, window, signif; int prot_ktup, prot_window, prot_signif; int gap_pos1, gap_pos2, mat_avscore; int nseqs, max_aa; #define MAX_ALN_LENGTH 5000 int *seqlen_array, def_aa_xref[NUMRES+1]; int *bench_output, *seq_output; double gap_open, gap_extend; double prot_gap_open, prot_gap_extend; double pw_go_penalty, pw_ge_penalty; double prot_pw_go_penalty, prot_pw_ge_penalty; char **args, **names, **seq_array; int matrix[NUMRES][NUMRES]; double gap_open_scale; double gap_extend_scale; // dnaFlag default value is false int dnaFlag = FALSE; // clustalw default value is false int clustalw = FALSE; #define INT_SCALE 100 #define MIN(a,b) ((a)<(b)?(a):(b)) #define tbgap(k) ((k) <= 0 ? 0 : tb + gh * (k)) #define tegap(k) ((k) <= 0 ? 0 : te + gh * (k)) /*********************************************************************** * : **********************************************************************/ void del(int k, int *print_ptr, int *last_print, int *displ) { if (*last_print<0) *last_print = displ[(*print_ptr)-1] -= k; else *last_print = displ[(*print_ptr)++] = -k; } /*********************************************************************** * : **********************************************************************/ void add(int v, int *print_ptr, int *last_print, int *displ) { if (*last_print < 0) { displ[(*print_ptr)-1] = v; displ[(*print_ptr)++] = *last_print; } else { *last_print = displ[(*print_ptr)++] = v; } } /*********************************************************************** * : **********************************************************************/ int calc_score(int iat, int jat, int v1, int v2, int seq1, int seq2) { int i, j, ipos, jpos; ipos = v1 + iat; jpos = v2 + jat; i = seq_array[seq1][ipos]; j = seq_array[seq2][jpos]; return (matrix[i][j]); } /*********************************************************************** * : **********************************************************************/ int get_matrix(int *matptr, int *xref, int scale) { int gg_score = 0; int gr_score = 0; int i, j, k, ti, tj, ix; int av1, av2, av3, min, max, maxres; for (i = 0; i <= max_aa; i++) for (j = 0; j <= max_aa; j++) matrix[i][j] = 0; ix = 0; maxres = 0; for (i = 0; i <= max_aa; i++) { ti = xref[i]; for (j = 0; j <= i; j++) { tj = xref[j]; if ((ti != -1) && (tj != -1)) { k = matptr[ix]; if (ti == tj) { matrix[ti][ti] = k * scale; maxres++; } else { matrix[ti][tj] = k * scale; matrix[tj][ti] = k * scale; } ix++; } } } maxres--; av1 = av2 = av3 = 0; for (i = 0; i <= max_aa; i++) { for (j = 0; j <= i; j++) { av1 += matrix[i][j]; if (i == j) av2 += matrix[i][j]; else av3 += matrix[i][j]; } } av1 /= (maxres*maxres)/2; av2 /= maxres; av3 /= (int) (((double)(maxres*maxres-maxres))/2); mat_avscore = -av3; min = max = matrix[0][0]; for (i = 0; i <= max_aa; i++) for (j = 1; j <= i; j++) { if (matrix[i][j] < min) min = matrix[i][j]; if (matrix[i][j] > max) max = matrix[i][j]; } for (i = 0; i < gap_pos1; i++) { matrix[i][gap_pos1] = gr_score; matrix[gap_pos1][i] = gr_score; matrix[i][gap_pos2] = gr_score; matrix[gap_pos2][i] = gr_score; } matrix[gap_pos1][gap_pos1] = gg_score; matrix[gap_pos2][gap_pos2] = gg_score; matrix[gap_pos2][gap_pos1] = gg_score; matrix[gap_pos1][gap_pos2] = gg_score; maxres += 2; return(maxres); } /*********************************************************************** * : **********************************************************************/ void forward_pass(char *ia, char *ib, int n, int m, int *se1, int *se2, int *maxscore, int g, int gh) { int i, j, f, p, t, hh; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; *maxscore = 0; *se1 = *se2 = 0; for (i = 0; i <= m; i++) {HH[i] = 0; DD[i] = -g;} for (i = 1; i <= n; i++) { hh = p = 0; f = -g; for (j = 1; j <= m; j++) { f -= gh; t = hh - g - gh; if (f < t) f = t; DD[j] -= gh; t = HH[j] - g - gh; if (DD[j] < t) DD[j] = t; hh = p + matrix[(int)ia[i]][(int)ib[j]]; if (hh < f) hh = f; if (hh < DD[j]) hh = DD[j]; if (hh < 0) hh = 0; p = HH[j]; HH[j] = hh; if (hh > *maxscore) {*maxscore = hh; *se1 = i; *se2 = j;} } } } /*********************************************************************** * : **********************************************************************/ void reverse_pass(char *ia, char *ib, int se1, int se2, int *sb1, int *sb2, int maxscore, int g, int gh) { int i, j, f, p, t, hh, cost; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; cost = 0; *sb1 = *sb2 = 1; for (i = se2; i > 0; i--){ HH[i] = -1; DD[i] = -1;} for (i = se1; i > 0; i--) { hh = f = -1; if (i == se1) p = 0; else p = -1; for (j = se2; j > 0; j--) { f -= gh; t = hh - g - gh; if (f < t) f = t; DD[j] -= gh; t = HH[j] - g - gh; if (DD[j] < t) DD[j] = t; hh = p + matrix[(int)ia[i]][(int)ib[j]]; if (hh < f) hh = f; if (hh < DD[j]) hh = DD[j]; p = HH[j]; HH[j] = hh; if (hh > cost) { cost = hh; *sb1 = i; *sb2 = j; if (cost >= maxscore) break; } } if (cost >= maxscore) break; } } /*********************************************************************** * : **********************************************************************/ int diff (int A, int B, int M, int N, int tb, int te, int *print_ptr, int *last_print, int *displ, int seq1, int seq2, int g, int gh) { int i, j, f, e, s, t, hh; int midi, midj, midh, type; int HH[MAX_ALN_LENGTH]; int DD[MAX_ALN_LENGTH]; int RR[MAX_ALN_LENGTH]; int SS[MAX_ALN_LENGTH]; if (N <= 0) {if (M > 0) del(M, print_ptr, last_print, displ); return( - (int) tbgap(M)); } if (M <= 1) { if (M <= 0) {add(N, print_ptr, last_print, displ); return( - (int)tbgap(N));} midh = -(tb+gh) - tegap(N); hh = -(te+gh) - tbgap(N); if (hh > midh) midh = hh; midj = 0; for (j = 1; j <= N; j++) { hh = calc_score(1,j,A,B,seq1,seq2) - tegap(N-j) - tbgap(j-1); if (hh > midh) {midh = hh; midj = j;} } if (midj == 0) { del(1, print_ptr, last_print, displ); add(N, print_ptr, last_print, displ); } else { if (midj > 1) add(midj-1, print_ptr, last_print, displ); displ[(*print_ptr)++] = *last_print = 0; if (midj < N) add(N-midj, print_ptr, last_print, displ); } return midh; } midi = M / 2; HH[0] = 0.0; t = -tb; for (j = 1; j <= N; j++) { HH[j] = t = t - gh; DD[j] = t - g; } t = -tb; for (i = 1; i <= midi; i++) { s = HH[0]; HH[0] = hh = t = t - gh; f = t - g; for (j = 1; j <= N; j++) { if ((hh = hh - g - gh) > (f = f - gh)) f = hh; if ((hh = HH[j] - g - gh) > (e = DD[j]- gh)) e = hh; hh = s + calc_score(i,j,A,B,seq1,seq2); if (f > hh) hh = f; if (e > hh) hh = e; s = HH[j]; HH[j] = hh; DD[j] = e; } } DD[0] = HH[0]; RR[N] = 0; t = -te; for (j = N-1; j >= 0; j--) {RR[j] = t = t - gh; SS[j] = t - g;} t = -te; for (i = M - 1; i >= midi; i--) { s = RR[N]; RR[N] = hh = t = t-gh; f = t - g; for (j = N - 1; j >= 0; j--) { if ((hh = hh - g - gh) > (f = f - gh)) f = hh; if ((hh = RR[j] - g - gh) > (e = SS[j] - gh)) e = hh; hh = s + calc_score(i+1,j+1,A,B,seq1,seq2); if (f > hh) hh = f; if (e > hh) hh = e; s = RR[j]; RR[j] = hh; SS[j] = e; } } SS[N] = RR[N]; midh = HH[0] + RR[0]; midj = 0; type = 1; for (j = 0; j <= N; j++) { hh = HH[j] + RR[j]; if (hh >= midh) if (hh > midh || (HH[j] != DD[j] && RR[j] == SS[j])) {midh = hh; midj = j;} } for (j = N; j >= 0; j--) { hh = DD[j] + SS[j] + g; if (hh > midh) {midh = hh;midj = j;type = 2;} } if (type == 1) { diff(A, B, midi, midj, tb, g, print_ptr, last_print, displ, seq1, seq2, g, gh); diff(A+midi, B+midj, M-midi, N-midj, g, te, print_ptr, last_print, displ, seq1, seq2, g, gh); } else { diff(A, B, midi-1, midj, tb, 0.0, print_ptr, last_print, displ, seq1, seq2, g, gh); del(2, print_ptr, last_print, displ); diff(A+midi+1, B+midj, M-midi-1, N-midj, 0.0, te, print_ptr, last_print, displ, seq1, seq2, g, gh); } return midh; } /*********************************************************************** * : **********************************************************************/ double tracepath(int tsb1, int tsb2, int *print_ptr, int *displ, int seq1, int seq2) { int i, k; int i1 = tsb1; int i2 = tsb2; int pos = 0; int count = 0; for (i = 1; i <= *print_ptr - 1; ++i) { if (displ[i]==0) { char c1 = seq_array[seq1][i1]; char c2 = seq_array[seq2][i2]; if ((c1!=gap_pos1) && (c1 != gap_pos2) && (c1 == c2)) count++; ++i1; ++i2; ++pos; } else if ((k = displ[i]) > 0) { i2 += k; pos += k; } else { i1 -= k; pos -= k; } } return (100.0 * (double) count); } int pairalign() { int i, n, m, si, sj; int len1, len2, maxres; double gg, mm_score; int *mat_xref, *matptr; matptr = gon250mt; mat_xref = def_aa_xref; maxres = get_matrix(matptr, mat_xref, 10); if (maxres == 0) return(-1); bots_message("Start aligning "); #pragma omp parallel { #pragma omp for schedule(dynamic) private(i,n,si,sj,len1,m) for (si = 0; si < nseqs; si++) { n = seqlen_array[si+1]; for (i = 1, len1 = 0; i <= n; i++) { char c = seq_array[si+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len1++; } for (sj = si + 1; sj < nseqs; sj++) { m = seqlen_array[sj+1]; if ( n == 0 || m == 0 ) { bench_output[si*nseqs+sj] = (int) 1.0; } else { #pragma omp task untied \ private(i,gg,len2,mm_score) firstprivate(m,n,si,sj,len1) \ shared(nseqs, bench_output,seqlen_array,seq_array,gap_pos1,gap_pos2,pw_ge_penalty,pw_go_penalty,mat_avscore) { int se1, se2, sb1, sb2, maxscore, seq1, seq2, g, gh; int displ[2*MAX_ALN_LENGTH+1]; int print_ptr, last_print; for (i = 1, len2 = 0; i <= m; i++) { char c = seq_array[sj+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len2++; } if ( dnaFlag == TRUE ) { g = (int) ( 2 * INT_SCALE * pw_go_penalty * gap_open_scale ); // gapOpen gh = (int) (INT_SCALE * pw_ge_penalty * gap_extend_scale); //gapExtend } else { gg = pw_go_penalty + log((double) MIN(n, m)); // temporary value g = (int) ((mat_avscore <= 0) ? (2 * INT_SCALE * gg) : (2 * mat_avscore * gg * gap_open_scale) ); // gapOpen gh = (int) (INT_SCALE * pw_ge_penalty); //gapExtend } seq1 = si + 1; seq2 = sj + 1; forward_pass(&seq_array[seq1][0], &seq_array[seq2][0], n, m, &se1, &se2, &maxscore, g, gh); reverse_pass(&seq_array[seq1][0], &seq_array[seq2][0], se1, se2, &sb1, &sb2, maxscore, g, gh); print_ptr = 1; last_print = 0; diff(sb1-1, sb2-1, se1-sb1+1, se2-sb2+1, 0, 0, &print_ptr, &last_print, displ, seq1, seq2, g, gh); mm_score = tracepath(sb1, sb2, &print_ptr, displ, seq1, seq2); if (len1 == 0 || len2 == 0) mm_score = 0.0; else mm_score /= (double) MIN(len1,len2); bench_output[si*nseqs+sj] = (int) mm_score; } // end task } // end if (n == 0 || m == 0) } // for (j) } // end parallel for (i) } // end parallel bots_message(" completed!\n"); return 0; } int pairalign_seq() { int i, n, m, si, sj; int len1, len2, maxres; double gg, mm_score; int *mat_xref, *matptr; matptr = gon250mt; mat_xref = def_aa_xref; maxres = get_matrix(matptr, mat_xref, 10); if (maxres == 0) return(-1); for (si = 0; si < nseqs; si++) { n = seqlen_array[si+1]; for (i = 1, len1 = 0; i <= n; i++) { char c = seq_array[si+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len1++; } for (sj = si + 1; sj < nseqs; sj++) { m = seqlen_array[sj+1]; if ( n == 0 || m == 0) { seq_output[si*nseqs+sj] = (int) 1.0; } else { int se1, se2, sb1, sb2, maxscore, seq1, seq2, g, gh; int displ[2*MAX_ALN_LENGTH+1]; int print_ptr, last_print; for (i = 1, len2 = 0; i <= m; i++) { char c = seq_array[sj+1][i]; if ((c != gap_pos1) && (c != gap_pos2)) len2++; } if ( dnaFlag == TRUE ) { g = (int) ( 2 * INT_SCALE * pw_go_penalty * gap_open_scale ); // gapOpen gh = (int) (INT_SCALE * pw_ge_penalty * gap_extend_scale); //gapExtend } else { gg = pw_go_penalty + log((double) MIN(n, m)); // temporary value g = (int) ((mat_avscore <= 0) ? (2 * INT_SCALE * gg) : (2 * mat_avscore * gg * gap_open_scale) ); // gapOpen gh = (int) (INT_SCALE * pw_ge_penalty); //gapExtend } seq1 = si + 1; seq2 = sj + 1; forward_pass(&seq_array[seq1][0], &seq_array[seq2][0], n, m, &se1, &se2, &maxscore, g, gh); reverse_pass(&seq_array[seq1][0], &seq_array[seq2][0], se1, se2, &sb1, &sb2, maxscore, g, gh); print_ptr = 1; last_print = 0; diff(sb1-1, sb2-1, se1-sb1+1, se2-sb2+1, 0, 0, &print_ptr, &last_print, displ, seq1, seq2, g, gh); mm_score = tracepath(sb1, sb2, &print_ptr, displ, seq1, seq2); if (len1 == 0 || len2 == 0) mm_score = 0.0; else mm_score /= (double) MIN(len1,len2); seq_output[si*nseqs+sj] = (int) mm_score; } } } return 0; } /*********************************************************************** * : **********************************************************************/ void init_matrix(void) { int i, j; char c1, c2; gap_pos1 = NUMRES - 2; gap_pos2 = NUMRES - 1; max_aa = strlen(amino_acid_codes) - 2; for (i = 0; i < NUMRES; i++) def_aa_xref[i] = -1; for (i = 0; (c1 = amino_acid_order[i]); i++) for (j = 0; (c2 = amino_acid_codes[j]); j++) if (c1 == c2) {def_aa_xref[i] = j; break;} } void pairalign_init (char *filename) { int i; if (!filename || !filename[0]) { bots_error(0, "Please specify an input file with the -f option\n"); } init_matrix(); nseqs = readseqs(filename); bots_message("Multiple Pairwise Alignment (%d sequences)\n", nseqs); for (i = 1; i <= nseqs; i++) bots_debug("Sequence %d: %s %6.d aa\n", i, names[i], seqlen_array[i]); if ( clustalw == TRUE ) { gap_open_scale = 0.6667; gap_extend_scale = 0.751; } else { gap_open_scale = 1.0; gap_extend_scale = 1.0; } if ( dnaFlag == TRUE ) { // Using DNA parameters ktup = 2; window = 4; signif = 4; gap_open = 15.00; gap_extend = 6.66; pw_go_penalty = 15.00; pw_ge_penalty = 6.66; } else { // Using protein parameters ktup = 1; window = 5; signif = 5; gap_open = 10.0; gap_extend = 0.2; pw_go_penalty = 10.0; pw_ge_penalty = 0.1; } } void align_init () { int i,j; bench_output = (int *) malloc(sizeof(int)*nseqs*nseqs); for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) bench_output[i*nseqs+j] = 0; } void align() { pairalign(); } void align_seq_init () { int i,j; seq_output = (int *) malloc(sizeof(int)*nseqs*nseqs); bench_output = (int *) malloc(sizeof(int)*nseqs*nseqs); for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) seq_output[i*nseqs+j] = 0; } void align_seq() { pairalign_seq(); } void align_end () { int i,j; for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) if (bench_output[i*nseqs+j] != 0) bots_debug("Benchmark sequences (%d:%d) Aligned. Score: %d\n", i+1 , j+1 , (int) bench_output[i*nseqs+j]); } int align_verify () { int i,j; int result = BOTS_RESULT_SUCCESSFUL; for(i = 0; i<nseqs; i++) for(j = 0; j<nseqs; j++) if (bench_output[i*nseqs+j] != seq_output[i*nseqs+j]) { bots_message("Error: Optimized prot. (%3d:%3d)=%5d Sequential prot. (%3d:%3d)=%5d\n", i+1, j+1, (int) bench_output[i*nseqs+j], i+1, j+1, (int) seq_output[i*nseqs+j]); result = BOTS_RESULT_UNSUCCESSFUL; } return result; }
ll_data_source.c
#include"llama/ll_data_source.h" virtual bool ll_simple_data_source::pull(ll_writable_graph* graph, size_t max_edges) { size_t num_stripes = omp_get_max_threads(); ll_la_request_queue* request_queues[num_stripes]; for (size_t i = 0; i < num_stripes; i++) { request_queues[i] = new ll_la_request_queue(); } bool loaded = false; size_t chunk = num_stripes <= 1 ? std::min<size_t>(10000ul, max_edges) : max_edges; while (true) { graph->tx_begin(); bool has_data = false; for (size_t i = 0; i < num_stripes; i++) request_queues[i]->shutdown_when_empty(false); #pragma omp parallel { if (omp_get_thread_num() == 0) { has_data = this->pull(request_queues, num_stripes, chunk); for (size_t i = 0; i < num_stripes; i++) request_queues[i]->shutdown_when_empty(); for (size_t i = 0; i < num_stripes; i++) request_queues[i]->run(*graph); } else { int t = omp_get_thread_num(); for (size_t i = 0; i < num_stripes; i++, t++) request_queues[t % num_stripes]->worker(*graph); } } graph->tx_commit(); if (has_data) loaded = true; else break; } for (size_t i = 0; i < num_stripes; i++) delete request_queues[i]; return loaded; }
nr_direct.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> //#include <omp.h> #include "config.h" #include "cint.h" #include "optimizer.h" #include "nr_direct.h" int GTOmax_shell_dim(const int *ao_loc, const int *shls_slice, int ncenter); int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); #define DECLARE_ALL \ const int *atm = envs->atm; \ const int *bas = envs->bas; \ const double *env = envs->env; \ const int natm = envs->natm; \ const int nbas = envs->nbas; \ const int *ao_loc = envs->ao_loc; \ const int *shls_slice = envs->shls_slice; \ const CINTOpt *cintopt = envs->cintopt; \ const int ioff = ao_loc[shls_slice[0]]; \ const int joff = ao_loc[shls_slice[2]]; \ const int koff = ao_loc[shls_slice[4]]; \ const int loff = ao_loc[shls_slice[6]]; \ const int i0 = ao_loc[ish] - ioff; \ const int j0 = ao_loc[jsh] - joff; \ const int i1 = ao_loc[ish+1] - ioff; \ const int j1 = ao_loc[jsh+1] - joff; \ const int di = i1 - i0; \ const int dj = j1 - j0; \ const int ncomp = envs->ncomp; \ const int dk = GTOmax_shell_dim(ao_loc, shls_slice+4, 2); \ double *cache = buf + di * dj * dk * dk * ncomp; \ int shls[4]; \ void (*pf)(double *eri, double *dm, JKArray *vjk, int *shls, \ int i0, int i1, int j0, int j1, \ int k0, int k1, int l0, int l1); \ int (*fprescreen)(); \ if (vhfopt) { \ fprescreen = vhfopt->fprescreen; \ } else { \ fprescreen = CVHFnoscreen; \ } \ int ksh, lsh, k0, k1, l0, l1, idm; #define INTOR_AND_CONTRACT \ if ((*fprescreen)(shls, vhfopt, atm, bas, env) \ && (*intor)(buf, NULL, shls, atm, natm, bas, nbas, env, \ cintopt, cache)) { \ k0 = ao_loc[ksh] - koff; \ l0 = ao_loc[lsh] - loff; \ k1 = ao_loc[ksh+1] - koff; \ l1 = ao_loc[lsh+1] - loff; \ for (idm = 0; idm < n_dm; idm++) { \ pf = jkop[idm]->contract; \ (*pf)(buf, dms[idm], vjk[idm], shls, \ i0, i1, j0, j1, k0, k1, l0, l1); \ } \ } /* * for given ksh, lsh, loop all ish, jsh */ void CVHFdot_nrs1(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { DECLARE_ALL; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const int lsh0 = shls_slice[6]; const int lsh1 = shls_slice[7]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh < lsh1; lsh++) { shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } } /* * for given ish, jsh, loop all ksh > lsh */ static void dot_nrs2sub(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { DECLARE_ALL; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const int lsh0 = shls_slice[6]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh <= ksh; lsh++) { shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } } void CVHFdot_nrs2ij(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish >= jsh) { CVHFdot_nrs1(intor, jkop, vjk, dms, buf, n_dm, ish, jsh, vhfopt, envs); } } void CVHFdot_nrs2kl(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { dot_nrs2sub(intor, jkop, vjk, dms, buf, n_dm, ish, jsh, vhfopt, envs); } void CVHFdot_nrs4(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish >= jsh) { dot_nrs2sub(intor, jkop, vjk, dms, buf, n_dm, ish, jsh, vhfopt, envs); } } void CVHFdot_nrs8(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, double *buf, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish < jsh) { return; } DECLARE_ALL; const int ksh0 = shls_slice[4]; const int lsh0 = shls_slice[6]; // to make fjk compatible to C-contiguous dm array, put ksh, lsh inner loop shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh <= ish; ksh++) { for (lsh = lsh0; lsh <= ksh; lsh++) { /* when ksh==ish, (lsh<jsh) misses some integrals (eg k<i&&l>j). * These integrals are calculated in the next (ish,jsh) pair. To show * that, we just need to prove that every elements in shell^4 appeared * only once in fjk_s8. */ if ((ksh == ish) && (lsh > jsh)) { break; } shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } } static void assemble_v(double *vjk, JKArray *jkarray, int *ao_loc) { int ish0 = jkarray->v_bra_sh0; int ish1 = jkarray->v_bra_sh1; int jsh0 = jkarray->v_ket_sh0; int jsh1 = jkarray->v_ket_sh1; int njsh = jsh1 - jsh0; int vrow = jkarray->v_dims[0]; int vcol = jkarray->v_dims[1]; int ncomp = jkarray->ncomp; int voffset = ao_loc[ish0] * vcol + ao_loc[jsh0]; int i, j, ish, jsh; int di, dj, icomp; int optr; double *data, *pv; for (ish = ish0; ish < ish1; ish++) { for (jsh = jsh0; jsh < jsh1; jsh++) { optr = jkarray->outptr[ish*njsh+jsh-jkarray->offset0_outptr]; if (optr != NOVALUE) { di = ao_loc[ish+1] - ao_loc[ish]; dj = ao_loc[jsh+1] - ao_loc[jsh]; data = jkarray->data + optr; pv = vjk + ao_loc[ish]*vcol+ao_loc[jsh] - voffset; for (icomp = 0; icomp < ncomp; icomp++) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { pv[i*vcol+j] += data[i*dj+j]; } } pv += vrow * vcol; data += di * dj; } } } } } /* * drv loop over ij, generate eris of kl for given ij, call fjk to * calculate vj, vk. * * n_dm is the number of dms for one [array(ij|kl)], it is also the size of dms and vjk * ncomp is the number of components that produced by intor * shls_slice = [ishstart, ishend, jshstart, jshend, kshstart, kshend, lshstart, lshend] * * ao_loc[i+1] = ao_loc[i] + CINTcgto_spheric(i, bas) for i = 0..nbas * * Return [(ptr[ncomp,nao,nao] in C-contiguous) for ptr in vjk] */ void CVHFnr_direct_drv(int (*intor)(), void (*fdot)(), JKOperator **jkop, double **dms, double **vjk, int n_dm, int ncomp, int *shls_slice, int *ao_loc, CINTOpt *cintopt, CVHFOpt *vhfopt, int *atm, int natm, int *bas, int nbas, double *env) { IntorEnvs envs = {natm, nbas, atm, bas, env, shls_slice, ao_loc, NULL, cintopt, ncomp}; int idm; size_t size; for (idm = 0; idm < n_dm; idm++) { size = jkop[idm]->data_size(shls_slice, ao_loc) * ncomp; memset(vjk[idm], 0, sizeof(double)*size); } const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; const int di = GTOmax_shell_dim(ao_loc, shls_slice, 4); const int cache_size = GTOmax_cache_size(intor, shls_slice, 4, atm, natm, bas, nbas, env); #pragma omp parallel default(none) \ shared(intor, fdot, jkop, ao_loc, shls_slice, \ dms, vjk, n_dm, ncomp, nbas, vhfopt, envs) { int i, j, ij, ij1; JKArray *v_priv[n_dm]; for (i = 0; i < n_dm; i++) { v_priv[i] = jkop[i]->allocate(shls_slice, ao_loc, ncomp); } double *buf = malloc(sizeof(double) * (di*di*di*di*ncomp + cache_size)); #pragma omp for nowait schedule(dynamic, 1) for (ij = 0; ij < nish*njsh; ij++) { ij1 = nish*njsh-1 - ij; // if (ij % 2) { ///* interlace the iteration to balance memory usage // * map [0,1,2...,N] to [0,N,1,N-1,...] */ // ij1 = nish*njsh-1 - ij/2; // } else { // ij1 = ij / 2; // } i = ij1 / njsh + ish0; j = ij1 % njsh + jsh0; (*fdot)(intor, jkop, v_priv, dms, buf, n_dm, i, j, vhfopt, &envs); } #pragma omp critical { for (i = 0; i < n_dm; i++) { assemble_v(vjk[i], v_priv[i], ao_loc); jkop[i]->deallocate(v_priv[i]); } } free(buf); } }
omp_ztrmm_batch.c
/** * @file omp_ztrmm_batch.c * * @brief BBLAS omp_ztrmm_batch double _Complex routine. * BBLAS is a software package provided by Univ. of Manchester, * Univ. of Tennessee. * * @version 1.0.0 * @author Samuel D. Relton * @author Pedro V. Lara * @author Mawussi Zounon * @date 2016-02-20 * **/ #ifndef DOXYGEN_SHOULD_SKIP_THIS /** * Code generation * @precisions normal z -> c d s **/ #endif #include<cblas.h> #include "bblas_omp.h" #include "bblas.h" #include <omp.h> #define COMPLEX /** Purpose ------- <b>ztrmm_batch</b> is an OpenMP version of ztrmm_batch. It perfoms one of the matrix-matrix operations arrayB[i] = alpha[i]*op( arrayA[i] )*arrayB[i], or arrayB[i] = alpha[i]*arrayB[i]*op( arrayA[i] ) where op( X ) is one of op( X ) = X or op( X ) = X**T or op( X ) = X**H, alpha[i] is a scalar, arrayB[i] is an M[i] by N[i] matrix, and arrayA[i] is a unit or non-unit, upper or lower triangular matrix. Fixed and Variable Batch Operations ----------------------------------- Two types of batch operation are supported depending upon the value of batch_opts. When <tt>batch_opts = BBLAS_VARIABLE</tt> - all parameters that are arrays must have length at least batch_count. - all parameters that are arrays must have all values set. When <tt>batch_opts = BBLAS_FIXED</tt> - all parameters that are arrays (except for arrayA, arrayB, and info) must have length at least one. - all parameters that are arrays (except for arrayA, arrayB, and info) need only to have their first value set. This means that for a <tt>BBLAS_FIXED</tt> batch, the values of side[0], uplo[0], M[0], N[0], transA[0], diag[0], alpha[0], lda[0], and ldb[0] are used for all computations. Parameters ---------- @param[in] side Array of <tt>enum BBLAS_SIDE</tt>. Each element side[i] specifies whether op( arrayA[i] ) multiplies arrayB[i] from left or right as follows: - = 'BblasLeft' arrayB[i] = alpha[i]*op( arrayA[i] )*arrayB[i]. - = 'BblasRight' arrayB[i] = alpha[i]*arrayB[i]*op( arrayA[i] ). @param[in] uplo Array of <tt>enum BBLAS_UPLO</tt>. On entry, uplo[i] specifies whether the matrix arrayA[i] is an upper or lower triangular matrix as follows: - = 'BblasUpper' arrayA[i] is an upper triangular matrix. - = 'BblasLower' arrayA[i] is a lower triangular matrix. @param[in] transA Array of <tt>enum BBLAS_TRANS</tt>. On entry, trans[i] specifies the form of op( arrayA[i] ) to be used in the matrix multiplication as follows: - = 'BblasNoTrans' op( arrayA[i] ) = arrayA[i]. - = 'BblasTrans' op( arrayA[i] ) = arrayA[i]**T. - = 'BblasConjTrans' op( arrayA[i] ) = arrayA[i]**H. @param[in] diag - Array of <tt>enum BBLAS_DIAG</tt>. On entry, diag[i] specifies whether or not arrayA[i] is unit triangular as follows: - = 'BblasUnit' arrayA[i] is assumed to be unit triangular. - = 'BblasNonUnit' arrayA[i] is not assumed to be unit triangular. @param[in] M Array of <tt>int</tt>. Each element M[i] specifies the number of rows of the matrix arrayB[i]. M[i] must be greater than zero. @param[in] N Array of <tt>int</tt>. Each element N[i] specifies the number of columns of the matrix arrayB[i]. N[i] must be greater than zero. @param[in] alpha Array of <tt>complex_16</tt>. @param[in] arrayA Array of pointers. Each element arrayA[i] is a pointer to a COMPLEX_16 matrix of dimension lda[i] by Ka[i], where Ka[i] = M[i] when side[i] = BblasLeft and is N[i] otherwise. When using side[i] = BblasLeft the M[i] by M[i] part of arrayA[i] must contain the triangular matrix: when uplo[i] = BblasUpper, the upper triangular part of arrayA[i] must contain the matrix whilst the strictly lower triangular part is not used; similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i] must contain the matrix whilst the strictly upper triangular part is not used. When using side[i] = BblasRight the N[i] by N[i] part of arrayA[i] must contain the symmetric matrix: when uplo[i] = BblasUpper, the upper triangular part of arrayA[i] must contain the matrix whilst the strictly lower triangular part is not used; similarly when uplo[i] = BblasLower, the lower triangular part of arrayA[i] must contain the matrix whilst the strictly upper triangular part is not used. Note that when diag = BblasUnit the diagonal elements of arrayA[i] are not used either, they are assumed to be equal to one. @param[in] lda Array of <tt>int</tt>. On entry, lda[i] specifies the first dimension of arrayA[i] as declared in the calling (sub) program. When side[i] = BblasLeft then lda[i] must be at least max( 1, M[i] ), otherwise lda[i] must be at least max( 1, N[i] ). @param[in,out] arrayB Array of pointers. Each element arrayB[i] is a pointer to a COMPLEX_16 matrix of dimension ldb[i] by N[i]. The leading M[i] by N[i] part of arrayB[i] must contain the matrix elements. On exit is arrayB[i] overwritten by the updated matrix. @param[in] ldb Array of <tt>int</tt>. Each element ldb[i] specifies the first dimension of arrayB[i] as declared in the calling (sub) program. Each element ldb[i] must be at least max( 1, M[i] ). @param[in] batch_count <tt>int</tt> The number of matrices to operate on. @param[in] batch_opts <tt>enum BBLAS_OPTS</tt> One of BBLAS_FIXED or BBLAS_VARIABLE depending upon the type of batch operation required. @param[out] info Array of <tt>int</tt>. Each element info[i] is the error return code of the ith ztrmm in the batch, these need not be set on entry. The error codes can be found in bblas_macros.h. **/ void omp_ztrmm_batch( const enum BBLAS_SIDE *side, const enum BBLAS_UPLO *uplo, const enum BBLAS_TRANS *transA, const enum BBLAS_DIAG *diag, const int *M, const int *N, const BBLAS_Complex64_t *alpha, const BBLAS_Complex64_t **arrayA, const int *lda, BBLAS_Complex64_t **arrayB, const int *ldb, const int batch_count, enum BBLAS_OPTS batch_opts, int *info) { /*Local variables */ int first_index = 0; int batch_iter; int LDA; char func_name[15] = "ztrmm_batch"; /* Check input arguments */ if (batch_count < 0) { xerbla_batch(func_name, BBLAS_ERR_BATCH_COUNT, -1); } if (batch_opts == BBLAS_FIXED) { if ((side[first_index] != BblasLeft) && (side[first_index] != BblasRight)) { xerbla_batch(func_name, BBLAS_ERR_SIDE, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_SIDE; } return; } if ((uplo[first_index] != BblasUpper) && (uplo[first_index] != BblasLower)) { xerbla_batch(func_name, BBLAS_ERR_UPLO, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_UPLO; } return; } if ((transA[first_index] != BblasNoTrans) && (transA[first_index] != BblasTrans) && (transA[first_index] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_TRANSA; } return; } if ((diag[first_index] != BblasNonUnit) && (diag[first_index] != BblasUnit)) { xerbla_batch(func_name, BBLAS_ERR_DIAG, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_DIAG; } return; } if (M[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_M; } return; } if (N[first_index] < 0) { xerbla_batch(func_name, BBLAS_ERR_N, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_N; } return; } if (side[first_index] == BblasLeft) { LDA = M[first_index]; } else { LDA = N[first_index]; } if (lda[first_index] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDA; } return; } if (ldb[first_index] < max(1, M[first_index])) { xerbla_batch(func_name, BBLAS_ERR_LDB, first_index); for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_ERR_LDB; } return; } /* particular case */ if (min(M[first_index], N[first_index]) == 0) { for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { info[batch_iter] = BBLAS_SUCCESS; } return; } #pragma omp parallel for private(batch_iter) for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { /*Call to cblas_ztrmm */ cblas_ztrmm( BblasColMajor, side[first_index], uplo[first_index], transA[first_index], diag[first_index], M[first_index], N[first_index], CBLAS_SADDR(alpha[first_index]), arrayA[batch_iter], lda[first_index], arrayB[batch_iter], ldb[first_index]); /* Successful */ info[batch_iter] = BBLAS_SUCCESS; } /*END FIXED SIZE FOR LOOP */ }else if (batch_opts == BBLAS_VARIABLE) { #pragma omp parallel for private(batch_iter, LDA) for (batch_iter = 0; batch_iter < batch_count; batch_iter++) { /* Check input arguments */ if ((side[batch_iter] != BblasLeft) && (side[batch_iter] != BblasRight)) { xerbla_batch(func_name, BBLAS_ERR_SIDE, batch_iter); info[batch_iter] = BBLAS_ERR_SIDE; continue; } if ((uplo[batch_iter] != BblasUpper) && (uplo[batch_iter] != BblasLower)) { xerbla_batch(func_name, BBLAS_ERR_UPLO, batch_iter); info[batch_iter] = BBLAS_ERR_UPLO; continue; } if ((transA[batch_iter] != BblasNoTrans) && (transA[batch_iter] != BblasTrans) && (transA[batch_iter] != BblasConjTrans)) { xerbla_batch(func_name, BBLAS_ERR_TRANSA, batch_iter); info[batch_iter] = BBLAS_ERR_TRANSA; continue; } if (M[batch_iter] < 0) { xerbla_batch(func_name, BBLAS_ERR_M, batch_iter); info[batch_iter] = BBLAS_ERR_M; continue; } if (N[batch_iter] < 0) { xerbla_batch(func_name,BBLAS_ERR_N, batch_iter); info[batch_iter] = BBLAS_ERR_N; continue; } if (side[batch_iter] == BblasLeft) { LDA = M[batch_iter]; } else { LDA = N[batch_iter]; } if (lda[batch_iter] < max(1, LDA)) { xerbla_batch(func_name, BBLAS_ERR_LDA, batch_iter); info[batch_iter] = BBLAS_ERR_LDA; continue; } if (ldb[batch_iter] < max(1, M[batch_iter])) { xerbla_batch(func_name, BBLAS_ERR_LDC, batch_iter); info[batch_iter] = BBLAS_ERR_LDC; continue; } /* particular case */ if (min(M[batch_iter], N[batch_iter]) == 0) { info[batch_iter] = BBLAS_SUCCESS; continue; } cblas_ztrmm( BblasColMajor, side[batch_iter], uplo[batch_iter], transA[batch_iter], diag[batch_iter], M[batch_iter], N[batch_iter], CBLAS_SADDR(alpha[batch_iter]), arrayA[batch_iter], lda[batch_iter], arrayB[batch_iter], ldb[batch_iter]); /* Successful */ info[batch_iter] = BBLAS_SUCCESS; } }else { xerbla_batch(func_name, BBLAS_ERR_BATCH_OPTS, -1); } } #undef COMPLEX
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/OpenMPClause.h" #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFENVHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static ParsedType getTypeAnnotation(const Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevPreferredType = P.PreferredType; PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// otherwise, it is a tag declaration. bool TemplateScope : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); static void LateTemplateParserCleanupCallback(void *P); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; struct ParsedAttributesViewWithRange : ParsedAttributesView { ParsedAttributesViewWithRange() : ParsedAttributesView() {} void clearListOnly() { ParsedAttributesView::clearListOnly(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc, if non-NULL, is filled with the location of the last token of // the simple-asm. ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); ExprResult ParseAsmStringLiteral(); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator(); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// Skip C++11 and C2x attributes and return the end location of the /// last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// Diagnose and skip C++11 and C2x attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// Parses a C++11 (or C2x)-style attribute argument list. Returns true /// if this results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewtypeAttribute(IdentifierInfo &SwiftNewtype, SourceLocation SwiftNewtypeLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); void ParsePtrauthQualifier(ParsedAttributes &Attrs); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( Declarator &D, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parses OpenMP context selectors and calls \p Callback for each /// successfully parsed context selector. bool parseOpenMPContextSelectors(SourceLocation Loc, SmallVectorImpl<Sema::OMPCtxSelectorData> &Data); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse clauses for '#pragma omp declare target'. DeclGroupPtrTy ParseOMPDeclareTargetClauses(); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc, bool IsAddressOfOperand = false); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; SmallVector<OpenMPMapModifierKind, OMPMapClause::NumberOfModifiers> MapTypeModifiers; SmallVector<SourceLocation, OMPMapClause::NumberOfModifiers> MapTypeModifiersLoc; OpenMPMapClauseKind MapType = OMPC_MAP_unknown; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); bool isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true); void AnnotateTemplateIdTokenAsType(bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); /// Parse the given string as a type. /// /// This is a dangerous utility function currently employed only by API notes. /// It is not a general entry-point for safely parsing types from strings. /// /// \param typeStr The string to be parsed as a type. /// \param context The name of the context in which this string is being /// parsed, which will be used in diagnostics. /// \param includeLoc The location at which this parse was triggered. TypeResult parseTypeFromString(StringRef typeStr, StringRef context, SourceLocation includeLoc); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); ExprResult ParseBuiltinPtrauthTypeDiscriminator(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
memory.c
void convert_memory(unsigned char *img, int width, int height, int channels, int threads, unsigned char *result) { int pixel_per_thread = (width * height) / threads; #pragma omp parallel for for (int thread = 0; thread < threads; thread++) { int end; if (thread + 1 == threads) { end = width * height; } else { end = pixel_per_thread * (thread + 1); } for (int i = pixel_per_thread * thread; i < end; i++) { result[i] = 0.2126 * img[(i * channels)] // red + 0.7152 * img[(i * channels) + 1] // green + 0.0722 * img[(i * channels) + 2]; // blue } } }
GB_unop__identity_int64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int64_fc64) // op(A') function: GB (_unop_tran__identity_int64_fc64) // C type: int64_t // A type: GxB_FC64_t // cast: int64_t cij = GB_cast_to_int64_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int64_t z = GB_cast_to_int64_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = GB_cast_to_int64_t (creal (aij)) ; \ 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_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int64_fc64) ( int64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t (creal (aij)) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; int64_t z = GB_cast_to_int64_t (creal (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
flush-2.c
int a, b; void foo (void) { #pragma omp flush #pragma omp flush (a, b) #pragma omp flush acquire #pragma omp flush release #pragma omp flush acq_rel #pragma omp flush relaxed /* { dg-error "expected 'acq_rel', 'release' or 'acquire'" } */ #pragma omp flush seq_cst /* { dg-error "expected 'acq_rel', 'release' or 'acquire'" } */ #pragma omp flush foobar /* { dg-error "expected 'acq_rel', 'release' or 'acquire'" } */ #pragma omp flush acquire (a, b) /* { dg-error "'flush' list specified together with memory order clause" } */ #pragma omp flush release (a, b) /* { dg-error "'flush' list specified together with memory order clause" } */ #pragma omp flush acq_rel (a, b) /* { dg-error "'flush' list specified together with memory order clause" } */ }
ntcopy.c
#include <tinyMatrixMul.h> #include <arm_neon.h> #include <string.h> #include "asmNeonApi.h" //#define USE_ASM_NTCOPY #ifdef STAND_ALONE_COMPILER static inline void vst1q_u32_x4(uint32_t *pDst, uint32x4x4_t src32x4x4) { vst1q_u32(pDst, src32x4x4.val[0]); vst1q_u32(pDst+4, src32x4x4.val[1]); vst1q_u32(pDst+8, src32x4x4.val[2]); vst1q_u32(pDst+12, src32x4x4.val[3]); } static inline void vst1_u32_x4(uint32_t *pDst, uint32x2x4_t src32x2x4) { vst1_u32(pDst, src32x2x4.val[0]); vst1_u32(pDst+2, src32x2x4.val[1]); vst1_u32(pDst+4, src32x2x4.val[2]); vst1_u32(pDst+6, src32x2x4.val[3]); } static inline void vst1q_u32_x2(uint32_t *pDst, uint32x4x2_t src32x4x2) { vst1q_u32(pDst, src32x4x2.val[0]); vst1q_u32(pDst+4, src32x4x2.val[1]); } #endif void tcopy_patch_4x4(const float *pSrc, uint32_t K, uint32_t M, uint32_t stride, float *pDst, uint32_t numThreads) { uint32_t i = 0, j = 0; uint32_t MDiv4, MHas2, MHas1, KDiv4, KHas2, KHas1; uint32_t *pSrcStart, *pDstStart; MDiv4 = M>>2; MHas2 = (M>>1)&1; MHas1 = M&1; KDiv4 = K>>2; KHas2 = (K>>1)&1; KHas1 = K&1; #if 0 printf("M: %d, k: %d stride: %d\n", M, K, stride); printf("KDiv4: %d, KHas2: %d KHas1: %d\n", KDiv4, KHas2, KHas1); printf("MDiv4: %d, MHas2: %d KMas1: %d\n", MDiv4, MHas2, MHas1); #endif for(j = 0; j < MDiv4; j++) { pSrcStart = (uint32_t *)pSrc + j*4*stride; pDstStart = (uint32_t *)pDst + j*4*K; #pragma omp parallel for num_threads(numThreads) schedule(static) for( i = 0; i < KDiv4; i++) { /* Do 4x4 patch copy */ #ifdef USE_ASM_NTCOPY tcopy_4x4_asm(pSrcStart + i*4, 4*stride, pDstStart + i*16); #else uint32x4x4_t vsrc_32x4x4; vsrc_32x4x4.val[0] = vld1q_u32(pSrcStart + i*4); vsrc_32x4x4.val[1] = vld1q_u32(pSrcStart + i*4 + stride); vsrc_32x4x4.val[2] = vld1q_u32(pSrcStart + i*4 + 2*stride); vsrc_32x4x4.val[3] = vld1q_u32(pSrcStart + i*4 + 3*stride); vst1q_u32_x4(pDstStart + i*16, vsrc_32x4x4); #endif } pSrcStart += KDiv4*4; pDstStart += KDiv4*16; if(KHas2) { /* Do 2x4 patch copy */ #ifdef USE_ASM_NTCOPY tcopy_2x4_asm(pSrcStart, 4*stride, pDstStart); #else uint32x2x4_t vsrc_32x2x4; vsrc_32x2x4.val[0] = vld1_u32(pSrcStart); vsrc_32x2x4.val[1] = vld1_u32(pSrcStart + stride); vsrc_32x2x4.val[2] = vld1_u32(pSrcStart + 2*stride); vsrc_32x2x4.val[3] = vld1_u32(pSrcStart + 3*stride); vst1_u32_x4(pDstStart, vsrc_32x2x4); #endif pSrcStart += 2; pDstStart += 8; } if(KHas1) { /* Do 1x4 patch copy */ #ifdef USE_ASM_NTCOPY tcopy_1x4_asm(pSrcStart, 4*stride, pDstStart); #else pDstStart[0] = *pSrcStart; pDstStart[1] = *(pSrcStart + stride); pDstStart[2] = *(pSrcStart + 2*stride); pDstStart[3] = *(pSrcStart + 3*stride); #endif } } if(MHas2) { pSrcStart = (uint32_t *)pSrc + MDiv4*4*stride; pDstStart = (uint32_t *)pDst + MDiv4*4*K; #pragma omp parallel for num_threads(numThreads) schedule(static) for( i = 0; i < KDiv4; i++) { /* Do 4x2 patch copy */ #ifdef USE_ASM_NTCOPY tcopy_4x2_asm(pSrcStart + i*4, 4*stride, pDstStart + i*8); #else uint32x4x2_t vsrc_32x4x2; vsrc_32x4x2.val[0] = vld1q_u32(pSrcStart + i*4); vsrc_32x4x2.val[1] = vld1q_u32(pSrcStart + i*4 + stride); vst1q_u32_x2(pDstStart + i*8, vsrc_32x4x2); #endif } pSrcStart += KDiv4*4; pDstStart += KDiv4*8; if(KHas2) { /* Do 2x2 patch copy */ *(pDstStart+0) = *(pSrcStart); *(pDstStart+1) = *(pSrcStart + 1); *(pDstStart+2) = *(pSrcStart + stride); *(pDstStart+3) = *(pSrcStart + stride + 1); pSrcStart += 2; pDstStart += 4; } if(KHas1) { /* Do 1x2 patch copy */ *(pDstStart+0) = *(pSrcStart); *(pDstStart+1) = *(pSrcStart + stride); } } if (MHas1) { pSrcStart = (uint32_t *)pSrc + (M-1)*stride; pDstStart = (uint32_t *)pDst + (M-1)*K; memcpy(pDstStart, pSrcStart, K*sizeof(*pSrc)); } } void ncopy_patch_4x4(const float *pSrc, uint32_t K, uint32_t N, uint32_t stride, float *pDst, uint32_t numThreads) { uint32_t i = 0, j = 0; uint32_t NDiv4, NHas2, NHas1, KDiv4, KHas2, KHas1; uint32_t *pSrcStart, *pDstStart; uint32_t *pDst2x4Start, *pDst1x4Start; NDiv4 = N>>2; NHas2 = (N>>1)&1; NHas1 = N&1; KDiv4 = K>>2; KHas2 = (K>>1)&1; KHas1 = K&1; pDst1x4Start = pDst2x4Start = (uint32_t *)pDst + 4*K*NDiv4; if(NHas2) pDst1x4Start = (uint32_t *)pDst2x4Start + 2*K; #if 0 printf("\nK: %d, N: %d STRIDE: %d\n", K, N, stride); printf("KDiv4: %d, KHas2: %d KHas1: %d\n", KDiv4, KHas2, KHas1); printf("NDiv4: %d, NHas2: %d NNas1: %d\n\n", NDiv4, NHas2, NHas1); #endif for(j = 0; j < KDiv4; j++) { pSrcStart = (uint32_t *)pSrc + j*4*stride; pDstStart = (uint32_t *)pDst + j*4*4; #pragma omp parallel for num_threads(numThreads) schedule(static) for( i = 0; i < NDiv4; i++) { /* Do 4x4 patch copy */ #ifdef USE_ASM_NTCOPY ncopy_4x4_asm(pSrcStart + i*4, 4*stride, pDstStart + i*4*K); #else uint32x4x4_t vsrc_32x4x4; vsrc_32x4x4.val[0] = vld1q_u32(pSrcStart + i*4); vsrc_32x4x4.val[1] = vld1q_u32(pSrcStart + i*4 + stride); vsrc_32x4x4.val[2] = vld1q_u32(pSrcStart + i*4 + 2*stride); vsrc_32x4x4.val[3] = vld1q_u32(pSrcStart + i*4 + 3*stride); vst1q_u32_x4(pDstStart + i*4*K, vsrc_32x4x4); #endif } pSrcStart += NDiv4*4; if(NHas2) { /* Do 2x4 patch copy */ #ifdef USE_ASM_NTCOPY ncopy_2x4_asm(pSrcStart, 4*stride, pDst2x4Start + j*8); #else uint32x2x4_t vsrc_32x2x4; vsrc_32x2x4.val[0] = vld1_u32(pSrcStart); vsrc_32x2x4.val[1] = vld1_u32(pSrcStart + stride); vsrc_32x2x4.val[2] = vld1_u32(pSrcStart + 2*stride); vsrc_32x2x4.val[3] = vld1_u32(pSrcStart + 3*stride); vst1_u32_x4(pDst2x4Start + j*8, vsrc_32x2x4); #endif pSrcStart += 2; } if(NHas1) { /* Do 1x4patch copy */ #ifdef USE_ASM_NTCOPY ncopy_1x4_asm(pSrcStart, 4*stride, pDst1x4Start + j*4); #else uint32_t *pDstStart = pDst1x4Start + j*4; pDstStart[0] = *pSrcStart; pDstStart[1] = *(pSrcStart + stride); pDstStart[2] = *(pSrcStart + 2*stride); pDstStart[3] = *(pSrcStart + 3*stride); #endif } } if(KHas2) { pSrcStart = (uint32_t *)pSrc + KDiv4*4*stride; pDstStart = (uint32_t *)pDst + KDiv4*4*4; #pragma omp parallel for num_threads(numThreads) schedule(static) for( i = 0; i < NDiv4; i++) { /* Do 4x2 patch copy */ #ifdef USE_ASM_NTCOPY ncopy_4x2_asm(pSrcStart + i*4, 4*stride, pDstStart + i*4*K); #else uint32x4x2_t vsrc_32x4x2; vsrc_32x4x2.val[0] = vld1q_u32(pSrcStart + i*4); vsrc_32x4x2.val[1] = vld1q_u32(pSrcStart + i*4 + stride); vst1q_u32_x2(pDstStart + i*4*K, vsrc_32x4x2); #endif } pSrcStart += NDiv4*4; if(NHas2) { uint32_t *pTmp = pDst2x4Start + KDiv4*8; /* Do 2x2 patch copy */ *(pTmp+0) = *(pSrcStart); *(pTmp+1) = *(pSrcStart + 1); *(pTmp+2) = *(pSrcStart + stride); *(pTmp+3) = *(pSrcStart + stride + 1); pSrcStart += 2; } if(NHas1) { uint32_t *pTmp = pDst1x4Start + KDiv4*4; /* Do 1x2 patch copy */ *(pTmp+0) = *(pSrcStart); *(pTmp+1) = *(pSrcStart + stride); } } if (KHas1) { pSrcStart = (uint32_t *)pSrc + (K-1)*stride; pDstStart = (uint32_t *)pDst + 4*4*KDiv4; if (KHas2) pDstStart += 2*4; #pragma omp parallel for num_threads(numThreads) schedule(static) for( i = 0; i < NDiv4; i++) { /* Do 4x1 patch copy */ #ifdef USE_ASM_NTCOPY ncopy_4x1_asm(pSrcStart + i*4, 4*stride, pDstStart + i*4*K); #else uint32x4_t vsrc_32x4; vsrc_32x4 = vld1q_u32(pSrcStart + i*4); vst1q_u32(pDstStart + i*4*K, vsrc_32x4); #endif } pSrcStart += NDiv4*4; if(NHas2) { uint32_t *pTmp = pDst2x4Start + KDiv4*8; if (KHas2) pTmp += 4; /* Do 2x1 patch copy */ *(pTmp+0) = *(pSrcStart); *(pTmp+1) = *(pSrcStart + 1); pSrcStart += 2; } if(NHas1) { *((uint32_t *)pDst + K*N - 1) = *(pSrcStart); } } }
trmv_x_sky_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t ONAME_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; const ALPHA_INT thread_num = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); } for(ALPHA_INT c = 0; c < n; ++c) { const ALPHA_INT col_start = A->pointers[c]; const ALPHA_INT col_end = A->pointers[c + 1]; ALPHA_INT col_indx = 1; for(ALPHA_INT ai = col_start; ai < col_end; ++ai) { ALPHA_INT col_eles = col_end - col_start; ALPHA_INT r = c - col_eles + col_indx; if(ai == col_end - 1) { alpha_madde(y[r], alpha, x[c]); } else { ALPHA_Number t; alpha_mul(t, alpha, A->values[ai]); alpha_madde(y[r], t, x[c]); } col_indx ++; } } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return ONAME_omp(alpha, A, x, beta, y); }
ocp_nlp_sqp_rti.c
/* * Copyright 2019 Gianluca Frison, Dimitris Kouzoupis, Robin Verschueren, * Andrea Zanelli, Niels van Duijkeren, Jonathan Frey, Tommaso Sartor, * Branimir Novoselnik, Rien Quirynen, Rezart Qelibari, Dang Doan, * Jonas Koenemann, Yutao Chen, Tobias Schöls, Jonas Schlagenhauf, Moritz Diehl * * This file is part of acados. * * The 2-Clause BSD License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE.; */ #include "acados/ocp_nlp/ocp_nlp_sqp_rti.h" // external #include <assert.h> #include <math.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #if defined(ACADOS_WITH_OPENMP) #include <omp.h> #endif // blasfeo #include "blasfeo/include/blasfeo_d_aux.h" #include "blasfeo/include/blasfeo_d_aux_ext_dep.h" #include "blasfeo/include/blasfeo_d_blas.h" // acados #include "acados/ocp_nlp/ocp_nlp_common.h" #include "acados/ocp_nlp/ocp_nlp_dynamics_cont.h" #include "acados/ocp_nlp/ocp_nlp_reg_common.h" #include "acados/ocp_qp/ocp_qp_common.h" #include "acados/utils/mem.h" #include "acados/utils/print.h" #include "acados/utils/timing.h" #include "acados/utils/types.h" #include "acados_c/ocp_qp_interface.h" /************************************************ * options ************************************************/ acados_size_t ocp_nlp_sqp_rti_opts_calculate_size(void *config_, void *dims_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_rti_opts); size += ocp_nlp_opts_calculate_size(config, dims); return size; } void *ocp_nlp_sqp_rti_opts_assign(void *config_, void *dims_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; char *c_ptr = (char *) raw_memory; ocp_nlp_sqp_rti_opts *opts = (ocp_nlp_sqp_rti_opts *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_rti_opts); opts->nlp_opts = ocp_nlp_opts_assign(config, dims, c_ptr); c_ptr += ocp_nlp_opts_calculate_size(config, dims); assert((char *) raw_memory + ocp_nlp_sqp_rti_opts_calculate_size(config, dims) >= c_ptr); return opts; } void ocp_nlp_sqp_rti_opts_initialize_default(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // ocp_nlp_dynamics_config **dynamics = config->dynamics; // ocp_nlp_constraints_config **constraints = config->constraints; // int ii; // int N = dims->N; // this first !!! ocp_nlp_opts_initialize_default(config, dims, nlp_opts); // SQP RTI opts opts->ext_qp_res = 0; opts->warm_start_first_qp = false; opts->rti_phase = 0; opts->print_level = 0; // overwrite default submodules opts // do not compute adjoint in dynamics and constraints // int compute_adj = 0; // // dynamics // for (ii = 0; ii < N; ii++) // { // dynamics[ii]->opts_set(dynamics[ii], // opts->nlp_opts->dynamics[ii], "compute_adj", &compute_adj); // } // // constraints // for (ii = 0; ii <= N; ii++) // { // constraints[ii]->opts_set(constraints[ii], // opts->nlp_opts->constraints[ii], "compute_adj", &compute_adj); // } return; } void ocp_nlp_sqp_rti_opts_update(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_update(config, dims, nlp_opts); return; } void ocp_nlp_sqp_rti_opts_set(void *config_, void *opts_, const char *field, void* value) { ocp_nlp_sqp_rti_opts *opts = (ocp_nlp_sqp_rti_opts *) opts_; ocp_nlp_config *config = config_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; int ii; char module[MAX_STR_LEN]; char *ptr_module = NULL; int module_length = 0; // extract module name char *char_ = strchr(field, '_'); if (char_!=NULL) { module_length = char_-field; for (ii=0; ii<module_length; ii++) module[ii] = field[ii]; module[module_length] = '\0'; // add end of string ptr_module = module; } // pass options to QP module if ( ptr_module!=NULL && (!strcmp(ptr_module, "qp")) ) { ocp_nlp_opts_set(config, nlp_opts, field, value); if (!strcmp(field, "qp_warm_start")) { int* i_ptr = (int *) value; opts->qp_warm_start = *i_ptr; } } else // nlp opts { if (!strcmp(field, "ext_qp_res")) { int* ext_qp_res = (int *) value; opts->ext_qp_res = *ext_qp_res; } else if (!strcmp(field, "warm_start_first_qp")) { bool* warm_start_first_qp = (bool *) value; opts->warm_start_first_qp = *warm_start_first_qp; } else if (!strcmp(field, "rti_phase")) { int* rti_phase = (int *) value; if (*rti_phase < 0 || *rti_phase > 2) { printf("\nerror: ocp_nlp_sqp_opts_set: invalid value for rti_phase field."); printf("possible values are: 0, 1, 2\n"); exit(1); } else opts->rti_phase = *rti_phase; } else if (!strcmp(field, "print_level")) { int* print_level = (int *) value; if (*print_level < 0) { printf("\nerror: ocp_nlp_sqp_rti_opts_set: invalid value for print_level field, need int >=0, got %d.", *print_level); exit(1); } opts->print_level = *print_level; } else { ocp_nlp_opts_set(config, nlp_opts, field, value); } } return; } void ocp_nlp_sqp_rti_opts_set_at_stage(void *config_, void *opts_, size_t stage, const char *field, void* value) { ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = (ocp_nlp_sqp_rti_opts *) opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_opts_set_at_stage(config, nlp_opts, stage, field, value); } /************************************************ * memory ************************************************/ acados_size_t ocp_nlp_sqp_rti_memory_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // ocp_nlp_dynamics_config **dynamics = config->dynamics; // ocp_nlp_cost_config **cost = config->cost; // ocp_nlp_constraints_config **constraints = config->constraints; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; acados_size_t size = 0; size += sizeof(ocp_nlp_sqp_rti_memory); // nlp mem size += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat int stat_m = 1+1; int stat_n = 2; if (opts->ext_qp_res) stat_n += 4; size += stat_n*stat_m*sizeof(double); size += 8; // initial align make_int_multiple_of(8, &size); return size; } void *ocp_nlp_sqp_rti_memory_assign(void *config_, void *dims_, void *opts_, void *raw_memory) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; // ocp_nlp_dynamics_config **dynamics = config->dynamics; // ocp_nlp_cost_config **cost = config->cost; // ocp_nlp_constraints_config **constraints = config->constraints; char *c_ptr = (char *) raw_memory; // int ii; // int N = dims->N; // int *nx = dims->nx; // int *nu = dims->nu; // int *nz = dims->nz; // initial align align_char_to(8, &c_ptr); ocp_nlp_sqp_rti_memory *mem = (ocp_nlp_sqp_rti_memory *) c_ptr; c_ptr += sizeof(ocp_nlp_sqp_rti_memory); // nlp mem mem->nlp_mem = ocp_nlp_memory_assign(config, dims, nlp_opts, c_ptr); c_ptr += ocp_nlp_memory_calculate_size(config, dims, nlp_opts); // stat mem->stat = (double *) c_ptr; mem->stat_m = 1+1; mem->stat_n = 2; if (opts->ext_qp_res) mem->stat_n += 4; c_ptr += mem->stat_m*mem->stat_n*sizeof(double); mem->status = ACADOS_READY; assert((char *) raw_memory+ocp_nlp_sqp_rti_memory_calculate_size( config, dims, opts) >= c_ptr); return mem; } /************************************************ * workspace ************************************************/ acados_size_t ocp_nlp_sqp_rti_workspace_calculate_size(void *config_, void *dims_, void *opts_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; acados_size_t size = 0; // sqp size += sizeof(ocp_nlp_sqp_rti_workspace); // nlp size += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // qp in size += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // qp out size += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res size += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws size += ocp_qp_res_workspace_calculate_size(dims->qp_solver->orig_dims); } return size; } static void ocp_nlp_sqp_rti_cast_workspace( ocp_nlp_config *config, ocp_nlp_dims *dims, ocp_nlp_sqp_rti_opts *opts, ocp_nlp_sqp_rti_memory *mem, ocp_nlp_sqp_rti_workspace *work) { ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_memory *nlp_mem = mem->nlp_mem; // sqp char *c_ptr = (char *) work; c_ptr += sizeof(ocp_nlp_sqp_rti_workspace); // nlp work->nlp_work = ocp_nlp_workspace_assign( config, dims, nlp_opts, nlp_mem, c_ptr); c_ptr += ocp_nlp_workspace_calculate_size(config, dims, nlp_opts); // qp in work->tmp_qp_in = ocp_qp_in_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_in_calculate_size(dims->qp_solver->orig_dims); // qp out work->tmp_qp_out = ocp_qp_out_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_out_calculate_size(dims->qp_solver->orig_dims); if (opts->ext_qp_res) { // qp res work->qp_res = ocp_qp_res_assign(dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_calculate_size(dims->qp_solver->orig_dims); // qp res ws work->qp_res_ws = ocp_qp_res_workspace_assign( dims->qp_solver->orig_dims, c_ptr); c_ptr += ocp_qp_res_workspace_calculate_size( dims->qp_solver->orig_dims); } assert((char *) work + ocp_nlp_sqp_rti_workspace_calculate_size(config, dims, opts) >= c_ptr); return; } /************************************************ * functions ************************************************/ int ocp_nlp_sqp_rti(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_sqp_rti_memory *mem = mem_; // zero timers acados_timer timer0; double total_time = 0.0; mem->time_tot = 0.0; ocp_nlp_sqp_rti_opts *nlp_opts = opts_; int rti_phase = nlp_opts->rti_phase; acados_tic(&timer0); switch(rti_phase) { // perform preparation and feedback rti_phase case 0: ocp_nlp_sqp_rti_preparation_step( config_, dims_, nlp_in_, nlp_out_, opts_, mem_, work_); ocp_nlp_sqp_rti_feedback_step( config_, dims_, nlp_in_, nlp_out_, opts_, mem_, work_); break; // perform preparation rti_phase case 1: ocp_nlp_sqp_rti_preparation_step( config_, dims_, nlp_in_, nlp_out_, opts_, mem_, work_); break; // perform feedback rti_phase case 2: ocp_nlp_sqp_rti_feedback_step( config_, dims_, nlp_in_, nlp_out_, opts_, mem_, work_); break; } total_time += acados_toc(&timer0); mem->time_tot = total_time; nlp_out->total_time = total_time; return mem->status; } void ocp_nlp_sqp_rti_preparation_step(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { acados_timer timer1; ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_sqp_rti_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; // ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_sqp_rti_workspace *work = work_; ocp_nlp_sqp_rti_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; mem->time_lin = 0.0; mem->time_reg = 0.0; int N = dims->N; int ii; #if defined(ACADOS_WITH_OPENMP) // backup number of threads int num_threads_bkp = omp_get_num_threads(); // set number of threads omp_set_num_threads(opts->nlp_opts->num_threads); #pragma omp parallel { // beginning of parallel region #endif // alias to dynamics_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for nowait #endif for (ii = 0; ii < N; ii++) { config->dynamics[ii]->memory_set_ux_ptr( nlp_out->ux+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_ux_ptr( nlp_work->tmp_nlp_out->ux+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_ux1_ptr( nlp_out->ux+ii+1, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_ux1_ptr( nlp_work->tmp_nlp_out->ux+ii+1, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_pi_ptr( nlp_out->pi+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_tmp_pi_ptr( nlp_work->tmp_nlp_out->pi+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_BAbt_ptr( nlp_mem->qp_in->BAbt+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_RSQrq_ptr( nlp_mem->qp_in->RSQrq+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_dzduxt_ptr( nlp_mem->dzduxt+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_sim_guess_ptr( nlp_mem->sim_guess+ii, nlp_mem->set_sim_guess+ii, nlp_mem->dynamics[ii]); config->dynamics[ii]->memory_set_z_alg_ptr( nlp_mem->z_alg+ii, nlp_mem->dynamics[ii]); } // alias to cost_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for nowait #endif for (ii = 0; ii <= N; ii++) { config->cost[ii]->memory_set_ux_ptr( nlp_out->ux+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_tmp_ux_ptr( nlp_work->tmp_nlp_out->ux+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_z_alg_ptr( nlp_mem->z_alg+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_dzdux_tran_ptr( nlp_mem->dzduxt+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_RSQrq_ptr( nlp_mem->qp_in->RSQrq+ii, nlp_mem->cost[ii]); config->cost[ii]->memory_set_Z_ptr( nlp_mem->qp_in->Z+ii, nlp_mem->cost[ii]); } // alias to constraints_memory #if defined(ACADOS_WITH_OPENMP) #pragma omp for nowait #endif for (ii = 0; ii <= N; ii++) { config->constraints[ii]->memory_set_ux_ptr( nlp_out->ux+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_tmp_ux_ptr( nlp_work->tmp_nlp_out->ux+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_lam_ptr( nlp_out->lam+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_tmp_lam_ptr( nlp_work->tmp_nlp_out->lam+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_z_alg_ptr( nlp_mem->z_alg+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_dzdux_tran_ptr( nlp_mem->dzduxt+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_DCt_ptr( nlp_mem->qp_in->DCt+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_RSQrq_ptr( nlp_mem->qp_in->RSQrq+ii, nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxb_ptr( nlp_mem->qp_in->idxb[ii], nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxs_rev_ptr( nlp_mem->qp_in->idxs_rev[ii], nlp_mem->constraints[ii]); config->constraints[ii]->memory_set_idxe_ptr( nlp_mem->qp_in->idxe[ii], nlp_mem->constraints[ii]); } // alias to regularize memory config->regularize->memory_set_RSQrq_ptr( dims->regularize, nlp_mem->qp_in->RSQrq, nlp_mem->regularize_mem); config->regularize->memory_set_rq_ptr( dims->regularize, nlp_mem->qp_in->rqz, nlp_mem->regularize_mem); config->regularize->memory_set_BAbt_ptr( dims->regularize, nlp_mem->qp_in->BAbt, nlp_mem->regularize_mem); config->regularize->memory_set_b_ptr( dims->regularize, nlp_mem->qp_in->b, nlp_mem->regularize_mem); config->regularize->memory_set_idxb_ptr( dims->regularize, nlp_mem->qp_in->idxb, nlp_mem->regularize_mem); config->regularize->memory_set_DCt_ptr( dims->regularize, nlp_mem->qp_in->DCt, nlp_mem->regularize_mem); config->regularize->memory_set_ux_ptr( dims->regularize, nlp_mem->qp_out->ux, nlp_mem->regularize_mem); config->regularize->memory_set_pi_ptr( dims->regularize, nlp_mem->qp_out->pi, nlp_mem->regularize_mem); config->regularize->memory_set_lam_ptr( dims->regularize, nlp_mem->qp_out->lam, nlp_mem->regularize_mem); // copy sampling times into dynamics model #if defined(ACADOS_WITH_OPENMP) #pragma omp for nowait #endif // NOTE(oj): this will lead in an error for irk_gnsf, T must be set in precompute; // -> remove here and make sure precompute is called everywhere (e.g. Python interface). for (ii = 0; ii < N; ii++) { config->dynamics[ii]->model_set(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], "T", nlp_in->Ts+ii); } #if defined(ACADOS_WITH_OPENMP) } // end of parallel region #endif // initialize QP ocp_nlp_initialize_qp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); /* SQP body */ int sqp_iter = 0; nlp_mem->sqp_iter = &sqp_iter; // linearizate NLP and update QP matrices acados_tic(&timer1); ocp_nlp_approximate_qp_matrices(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); mem->time_lin += acados_toc(&timer1); #if defined(ACADOS_WITH_OPENMP) // restore number of threads omp_set_num_threads(num_threads_bkp); #endif return; } void ocp_nlp_sqp_rti_feedback_step(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { acados_timer timer1; ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_opts *nlp_opts = opts->nlp_opts; ocp_nlp_sqp_rti_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_qp_xcond_solver_config *qp_solver = config->qp_solver; ocp_nlp_sqp_rti_workspace *work = work_; ocp_nlp_sqp_rti_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; int qp_iter = 0; int qp_status = 0; double tmp_time; mem->time_qp_sol = 0.0; mem->time_qp_solver_call = 0.0; mem->time_qp_xcond = 0.0; mem->time_glob = 0.0; // embed initial value (this actually updates all bounds at stage 0...) ocp_nlp_embed_initial_value(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // update QP rhs for SQP (step prim var, abs dual var) ocp_nlp_approximate_qp_vectors_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); // regularize Hessian acados_tic(&timer1); config->regularize->regularize_hessian(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); if (opts->print_level > 0) { printf("\n------- qp_in --------\n"); print_ocp_qp_in(nlp_mem->qp_in); } if (!opts->warm_start_first_qp) { int tmp_int = 0; config->qp_solver->opts_set(config->qp_solver, opts->nlp_opts->qp_solver_opts, "warm_start", &tmp_int); } // solve qp acados_tic(&timer1); qp_status = qp_solver->evaluate(qp_solver, dims->qp_solver, nlp_mem->qp_in, nlp_mem->qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); mem->time_qp_sol += acados_toc(&timer1); qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_solver_call", &tmp_time); mem->time_qp_solver_call += tmp_time; qp_solver->memory_get(qp_solver, nlp_mem->qp_solver_mem, "time_qp_xcond", &tmp_time); mem->time_qp_xcond += tmp_time; // compute correct dual solution in case of Hessian regularization acados_tic(&timer1); config->regularize->correct_dual_sol(config->regularize, dims->regularize, opts->nlp_opts->regularize, nlp_mem->regularize_mem); mem->time_reg += acados_toc(&timer1); // TODO move into QP solver memory ??? qp_info *qp_info_; ocp_qp_out_get(nlp_mem->qp_out, "qp_info", &qp_info_); nlp_out->qp_iter = qp_info_->num_iter; qp_iter = qp_info_->num_iter; // compute external QP residuals (for debugging) if (opts->ext_qp_res) { ocp_qp_res_compute(nlp_mem->qp_in, nlp_mem->qp_out, work->qp_res, work->qp_res_ws); ocp_qp_res_compute_nrm_inf(work->qp_res, mem->stat+(mem->stat_n*1+2)); // printf("\nsqp_iter %d, res %e %e %e %e\n", sqp_iter, // inf_norm_qp_res[0], inf_norm_qp_res[1], // inf_norm_qp_res[2], inf_norm_qp_res[3]); } // printf("\n------- qp_out (sqp iter %d) ---------\n", sqp_iter); // print_ocp_qp_out(nlp_mem->qp_out); // exit(1); // save statistics mem->stat[mem->stat_n*1+0] = qp_status; mem->stat[mem->stat_n*1+1] = qp_iter; if ((qp_status!=ACADOS_SUCCESS) & (qp_status!=ACADOS_MAXITER)) { // print_ocp_qp_in(mem->qp_in); #ifndef ACADOS_SILENT printf("\nSQP_RTI: QP solver returned error status %d QP iteration %d.\n", qp_status, qp_iter); #endif if (opts->print_level > 0) { printf("\n Failed to solve the following QP:\n"); print_ocp_qp_in(nlp_mem->qp_in); } mem->status = ACADOS_QP_FAILURE; return; } // globalization acados_tic(&timer1); double alpha = ocp_nlp_line_search(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work); mem->time_glob += acados_toc(&timer1); // update variables ocp_nlp_update_variables_sqp(config, dims, nlp_in, nlp_out, nlp_opts, nlp_mem, nlp_work, alpha); // ocp_nlp_dims_print(nlp_out->dims); // ocp_nlp_out_print(nlp_out); // exit(1); // print_ocp_qp_in(mem->qp_in); mem->status = ACADOS_SUCCESS; } int ocp_nlp_sqp_rti_precompute(void *config_, void *dims_, void *nlp_in_, void *nlp_out_, void *opts_, void *mem_, void *work_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_sqp_rti_memory *mem = mem_; ocp_nlp_in *nlp_in = nlp_in_; // ocp_nlp_out *nlp_out = nlp_out_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_sqp_rti_workspace *work = work_; ocp_nlp_sqp_rti_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; int N = dims->N; int status = ACADOS_SUCCESS; int ii; // TODO(giaf) flag to enable/disable checks for (ii = 0; ii <= N; ii++) { int module_val; config->constraints[ii]->dims_get(config->constraints[ii], dims->constraints[ii], "ns", &module_val); if (dims->ns[ii] != module_val) { printf("ocp_nlp_sqp_rti_precompute: inconsistent dimension ns \ for stage %d with constraint module, got %d, module: %d.", ii, dims->ns[ii], module_val); exit(1); } } // precompute for (ii = 0; ii < N; ii++) { // set T config->dynamics[ii]->model_set(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], "T", nlp_in->Ts+ii); // dynamics precompute status = config->dynamics[ii]->precompute(config->dynamics[ii], dims->dynamics[ii], nlp_in->dynamics[ii], opts->nlp_opts->dynamics[ii], nlp_mem->dynamics[ii], nlp_work->dynamics[ii]); if (status != ACADOS_SUCCESS) return status; } return status; } void ocp_nlp_sqp_rti_eval_param_sens(void *config_, void *dims_, void *opts_, void *mem_, void *work_, char *field, int stage, int index, void *sens_nlp_out_) { ocp_nlp_dims *dims = dims_; ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; ocp_nlp_sqp_rti_memory *mem = mem_; ocp_nlp_memory *nlp_mem = mem->nlp_mem; ocp_nlp_out *sens_nlp_out = sens_nlp_out_; ocp_nlp_sqp_rti_workspace *work = work_; ocp_nlp_sqp_rti_cast_workspace(config, dims, opts, mem, work); ocp_nlp_workspace *nlp_work = work->nlp_work; d_ocp_qp_copy_all(nlp_mem->qp_in, work->tmp_qp_in); d_ocp_qp_set_rhs_zero(work->tmp_qp_in); double one = 1.0; if ((!strcmp("ex", field)) & (stage==0)) { d_ocp_qp_set_el("lbx", stage, index, &one, work->tmp_qp_in); d_ocp_qp_set_el("ubx", stage, index, &one, work->tmp_qp_in); // d_ocp_qp_print(work->tmp_qp_in->dim, work->tmp_qp_in); config->qp_solver->eval_sens(config->qp_solver, dims->qp_solver, work->tmp_qp_in, work->tmp_qp_out, opts->nlp_opts->qp_solver_opts, nlp_mem->qp_solver_mem, nlp_work->qp_work); // d_ocp_qp_sol_print(work->tmp_qp_out->dim, work->tmp_qp_out); // exit(1); /* copy tmp_qp_out into sens_nlp_out */ int i; int N = dims->N; int *nv = dims->nv; int *nx = dims->nx; // int *nu = dims->nu; int *ni = dims->ni; // int *nz = dims->nz; for (i = 0; i <= N; i++) { blasfeo_dveccp(nv[i], work->tmp_qp_out->ux + i, 0, sens_nlp_out->ux + i, 0); if (i < N) blasfeo_dveccp(nx[i + 1], work->tmp_qp_out->pi + i, 0, sens_nlp_out->pi + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->lam + i, 0, sens_nlp_out->lam + i, 0); blasfeo_dveccp(2 * ni[i], work->tmp_qp_out->t + i, 0, sens_nlp_out->t + i, 0); } } else { printf("\nerror: field %s at stage %d not available in \ ocp_nlp_sqp_rti_eval_param_sens\n", field, stage); exit(1); } return; } // TODO rename memory_get ??? void ocp_nlp_sqp_rti_get(void *config_, void *dims_, void *mem_, const char *field, void *return_value_) { ocp_nlp_config *config = config_; ocp_nlp_dims *dims = dims_; ocp_nlp_sqp_rti_memory *mem = mem_; if (!strcmp("sqp_iter", field)) { int *value = return_value_; *value = 1; } else if (!strcmp("status", field)) { int *value = return_value_; *value = mem->status; } else if (!strcmp("time_tot", field) || !strcmp("tot_time", field)) { double *value = return_value_; *value = mem->time_tot; } else if (!strcmp("time_qp_sol", field) || !strcmp("time_qp", field)) { double *value = return_value_; *value = mem->time_qp_sol; } else if (!strcmp("time_qp_solver", field) || !strcmp("time_qp_solver_call", field)) { double *value = return_value_; *value = mem->time_qp_solver_call; } else if (!strcmp("time_qp_xcond", field)) { double *value = return_value_; *value = mem->time_qp_xcond; } else if (!strcmp("time_lin", field)) { double *value = return_value_; *value = mem->time_lin; } else if (!strcmp("time_reg", field)) { double *value = return_value_; *value = mem->time_reg; } else if (!strcmp("time_glob", field)) { double *value = return_value_; *value = mem->time_glob; } else if (!strcmp("time_sim", field) || !strcmp("time_sim_ad", field) || !strcmp("time_sim_la", field)) { double tmp = 0.0; double *ptr = return_value_; int N = dims->N; int ii; *ptr = 0.0; for (ii=0; ii<N; ii++) { config->dynamics[ii]->memory_get(config->dynamics[ii], dims->dynamics[ii], mem->nlp_mem->dynamics[ii], field, &tmp); *ptr += tmp; } } else if (!strcmp("stat", field)) { double **value = return_value_; *value = mem->stat; } else if (!strcmp("statistics", field)) { int n_row = 2; double *value = return_value_; for (int ii=0; ii<n_row; ii++) { value[ii+0] = ii; for (int jj=0; jj<mem->stat_n; jj++) value[ii+(jj+1)*n_row] = mem->stat[jj+ii*mem->stat_n]; } } else if (!strcmp("stat_m", field)) { int *value = return_value_; *value = mem->stat_m; } else if (!strcmp("stat_n", field)) { int *value = return_value_; *value = mem->stat_n; } else if (!strcmp("nlp_mem", field)) { void **value = return_value_; *value = mem->nlp_mem; } else if (!strcmp("qp_xcond_dims", field)) { void **value = return_value_; *value = dims->qp_solver->xcond_dims; } else if (!strcmp("nlp_res", field)) { ocp_nlp_res **value = return_value_; *value = mem->nlp_mem->nlp_res; } else if (!strcmp("qp_xcond_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_in; } else if (!strcmp("qp_xcond_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_solver_mem->xcond_qp_out; } else if (!strcmp("qp_in", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_in; } else if (!strcmp("qp_out", field)) { void **value = return_value_; *value = mem->nlp_mem->qp_out; } else if (!strcmp("qp_iter", field)) { config->qp_solver->memory_get(config->qp_solver, mem->nlp_mem->qp_solver_mem, "iter", return_value_); } else if (!strcmp("res_stat", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_stat; } else if (!strcmp("res_eq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_eq; } else if (!strcmp("res_ineq", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_ineq; } else if (!strcmp("res_comp", field)) { double *value = return_value_; *value = mem->nlp_mem->nlp_res->inf_norm_res_comp; } else if (!strcmp("cost_value", field)) { double *value = return_value_; *value = mem->nlp_mem->cost_value; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_rti_get\n", field); exit(1); } } void ocp_nlp_sqp_rti_opts_get(void *config_, void *dims_, void *opts_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_opts *opts = opts_; if (!strcmp("nlp_opts", field)) { void **value = return_value_; *value = opts->nlp_opts; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_rti_opts_get\n", field); exit(1); } } void ocp_nlp_sqp_rti_work_get(void *config_, void *dims_, void *work_, const char *field, void *return_value_) { // ocp_nlp_config *config = config_; ocp_nlp_sqp_rti_workspace *work = work_; if (!strcmp("nlp_work", field)) { void **value = return_value_; *value = work->nlp_work; } else { printf("\nerror: field %s not available in ocp_nlp_sqp_rti_work_get\n", field); exit(1); } } void ocp_nlp_sqp_rti_config_initialize_default(void *config_) { ocp_nlp_config *config = (ocp_nlp_config *) config_; config->opts_calculate_size = &ocp_nlp_sqp_rti_opts_calculate_size; config->opts_assign = &ocp_nlp_sqp_rti_opts_assign; config->opts_initialize_default = &ocp_nlp_sqp_rti_opts_initialize_default; config->opts_update = &ocp_nlp_sqp_rti_opts_update; config->opts_set = &ocp_nlp_sqp_rti_opts_set; config->opts_set_at_stage = &ocp_nlp_sqp_rti_opts_set_at_stage; config->memory_calculate_size = &ocp_nlp_sqp_rti_memory_calculate_size; config->memory_assign = &ocp_nlp_sqp_rti_memory_assign; config->workspace_calculate_size = &ocp_nlp_sqp_rti_workspace_calculate_size; config->evaluate = &ocp_nlp_sqp_rti; config->eval_param_sens = &ocp_nlp_sqp_rti_eval_param_sens; config->config_initialize_default = &ocp_nlp_sqp_rti_config_initialize_default; config->precompute = &ocp_nlp_sqp_rti_precompute; config->get = &ocp_nlp_sqp_rti_get; config->opts_get = &ocp_nlp_sqp_rti_opts_get; config->work_get = &ocp_nlp_sqp_rti_work_get; return; }
omp_taskwait.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <math.h> #include "omp_testsuite.h" #include "omp_my_sleep.h" int test_omp_taskwait() { int result1 = 0; /* Stores number of not finished tasks after the taskwait */ int result2 = 0; /* Stores number of wrong array elements at the end */ int array[NUM_TASKS]; int i; /* fill array */ for (i = 0; i < NUM_TASKS; i++) array[i] = 0; #pragma omp parallel { #pragma omp single { for (i = 0; i < NUM_TASKS; i++) { /* First we have to store the value of the loop index in a new variable * which will be private for each task because otherwise it will be overwritten * if the execution of the task takes longer than the time which is needed to * enter the next step of the loop! */ int myi; myi = i; #pragma omp task { my_sleep (SLEEPTIME); array[myi] = 1; } /* end of omp task */ } /* end of for */ #pragma omp taskwait /* check if all tasks were finished */ for (i = 0; i < NUM_TASKS; i++) if (array[i] != 1) result1++; /* generate some more tasks which now shall overwrite * the values in the tids array */ for (i = 0; i < NUM_TASKS; i++) { int myi; myi = i; #pragma omp task { array[myi] = 2; } /* end of omp task */ } /* end of for */ } /* end of single */ } /*end of parallel */ /* final check, if all array elements contain the right values: */ for (i = 0; i < NUM_TASKS; i++) { if (array[i] != 2) result2++; } return ((result1 == 0) && (result2 == 0)); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_taskwait()) { num_failed++; } } return num_failed; }
graph.h
// copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef GRAPH_H_ #define GRAPH_H_ #include <stdio.h> #include <cinttypes> #include <iostream> #include <type_traits> #include <map> #include "pvector.h" #include "util.h" #include "segmentgraph.h" #include <memory> #include <assert.h> /* GAP Benchmark Suite Class: CSRGraph Author: Scott Beamer Simple container for graph in CSR format - Intended to be constructed by a Builder - To make weighted, set DestID_ template type to NodeWeight - MakeInverse parameter controls whether graph stores its inverse */ // Used to hold node & weight, with another node it makes a weighted edge template <typename NodeID_=int32_t, typename WeightT_=int32_t> struct NodeWeight { NodeID_ v; WeightT_ w; NodeWeight() {} NodeWeight(NodeID_ v) : v(v), w(1) {} NodeWeight(NodeID_ v, WeightT_ w) : v(v), w(w) {} bool operator< (const NodeWeight& rhs) const { return v == rhs.v ? w < rhs.w : v < rhs.v; } // doesn't check WeightT_s, needed to remove duplicate edges bool operator== (const NodeWeight& rhs) const { return v == rhs.v; } // doesn't check WeightT_s, needed to remove self edges bool operator== (const NodeID_& rhs) const { return v == rhs; } operator NodeID_() { return v; } }; template <typename NodeID_, typename WeightT_> std::ostream& operator<<(std::ostream& os, const NodeWeight<NodeID_, WeightT_>& nw) { os << nw.v << " " << nw.w; return os; } template <typename NodeID_, typename WeightT_> std::istream& operator>>(std::istream& is, NodeWeight<NodeID_, WeightT_>& nw) { is >> nw.v >> nw.w; return is; } // Syntatic sugar for an edge template <typename SrcT, typename DstT = SrcT> struct EdgePair { SrcT u; DstT v; EdgePair() {} EdgePair(SrcT u, DstT v) : u(u), v(v) {} }; // SG = serialized graph, these types are for writing graph to file typedef int32_t SGID; typedef EdgePair<SGID> SGEdge; typedef int64_t SGOffset; template <class NodeID_, class DestID_ = NodeID_, bool MakeInverse = true> class CSRGraph { // Used to access neighbors of vertex, basically sugar for iterators class Neighborhood { NodeID_ n_; DestID_** g_index_; public: Neighborhood(NodeID_ n, DestID_** g_index) : n_(n), g_index_(g_index) {} typedef DestID_* iterator; iterator begin() { return g_index_[n_]; } iterator end() { return g_index_[n_+1]; } }; void ReleaseResources() { //added a second condition to prevent double free (transpose graphs) /* if (out_index_ != nullptr) delete[] out_index_; if (out_neighbors_ != nullptr) delete[] out_neighbors_; if (directed_) { if (in_index_ != nullptr && in_index_ != out_index_) delete[] in_index_; if (in_neighbors_ != nullptr && in_neighbors_ != out_neighbors_) delete[] in_neighbors_; } if (flags_ != nullptr) delete[] flags_; */ out_index_shared_.reset(); out_neighbors_shared_.reset(); in_index_shared_.reset(); in_neighbors_shared_.reset(); flags_shared_.reset(); offsets_shared_.reset(); for (auto iter = label_to_segment.begin(); iter != label_to_segment.end(); iter++) { delete ((*iter).second); } } public: CSRGraph() : directed_(false), num_nodes_(-1), num_edges_(-1), out_index_(nullptr), out_neighbors_(nullptr), in_index_(nullptr), in_neighbors_(nullptr), flags_(nullptr), is_transpose_(false) {} CSRGraph(int64_t num_nodes, DestID_** index, DestID_* neighs) : directed_(false), num_nodes_(num_nodes), out_index_(index), out_neighbors_(neighs), in_index_(index), in_neighbors_(neighs){ out_index_shared_.reset(index); out_neighbors_shared_.reset(neighs); in_index_shared_ = out_index_shared_; in_neighbors_shared_ = out_neighbors_shared_; num_edges_ = (out_index_[num_nodes_] - out_index_[0]) / 2; //adding flags used for deduplication flags_ = new int[num_nodes_]; flags_shared_.reset(flags_); //adding offsets for load balacne scheme SetUpOffsets(true); //Set this up for getting random neighbors srand(time(NULL)); } CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs, DestID_** in_index, DestID_* in_neighs) : directed_(true), num_nodes_(num_nodes), out_index_(out_index), out_neighbors_(out_neighs), in_index_(in_index), in_neighbors_(in_neighs), is_transpose_(false){ num_edges_ = out_index_[num_nodes_] - out_index_[0]; out_index_shared_.reset(out_index); out_neighbors_shared_.reset(out_neighs); in_index_shared_.reset(in_index); in_neighbors_shared_.reset(in_neighs); flags_ = new int[num_nodes_]; flags_shared_.reset(flags_); SetUpOffsets(true); //Set this up for getting random neighbors srand(time(NULL)); } CSRGraph(int64_t num_nodes, DestID_** out_index, DestID_* out_neighs, DestID_** in_index, DestID_* in_neighs, bool is_transpose) : directed_(true), num_nodes_(num_nodes), out_index_(out_index), out_neighbors_(out_neighs), in_index_(in_index), in_neighbors_(in_neighs) , is_transpose_(is_transpose){ num_edges_ = out_index_[num_nodes_] - out_index_[0]; out_index_shared_.reset(out_index); out_neighbors_shared_.reset(out_neighs); in_index_shared_.reset(in_index); in_neighbors_shared_.reset(in_neighs); flags_ = new int[num_nodes_]; flags_shared_.reset(flags_); SetUpOffsets(true); //Set this up for getting random neighbors srand(time(NULL)); } CSRGraph(int64_t num_nodes, std::shared_ptr<DestID_*> out_index, std::shared_ptr<DestID_> out_neighs, shared_ptr<DestID_*> in_index, shared_ptr<DestID_> in_neighs, bool is_transpose) : directed_(true), num_nodes_(num_nodes), out_index_(out_index.get()), out_neighbors_(out_neighs.get()), in_index_(in_index.get()), in_neighbors_(in_neighs.get()) , is_transpose_(is_transpose){ num_edges_ = out_index_[num_nodes_] - out_index_[0]; out_index_shared_ = (out_index); out_neighbors_shared_ = (out_neighs); in_index_shared_ = (in_index); in_neighbors_shared_ = (in_neighs); flags_ = new int[num_nodes_]; flags_shared_.reset(flags_); SetUpOffsets(true); //Set this up for getting random neighbors srand(time(NULL)); } CSRGraph(CSRGraph& other) : directed_(other.directed_), num_nodes_(other.num_nodes_), num_edges_(other.num_edges_), out_index_(other.out_index_), out_neighbors_(other.out_neighbors_), in_index_(other.in_index_), in_neighbors_(other.in_neighbors_), is_transpose_(false){ /* Commenting this because object is not taking owner ship of the elements, notice destructor_free is set to false other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; other.flags_ = nullptr; other.offsets_ = nullptr; */ out_index_shared_ = other.out_index_shared_; out_neighbors_shared_ = other.out_neighbors_shared_; in_index_shared_ = other.in_index_shared_; in_neighbors_shared_ = other.in_neighbors_shared_; //Set this up for getting random neighbors srand(time(NULL)); } CSRGraph(CSRGraph&& other) : directed_(other.directed_), num_nodes_(other.num_nodes_), num_edges_(other.num_edges_), out_index_(other.out_index_), out_neighbors_(other.out_neighbors_), in_index_(other.in_index_), in_neighbors_(other.in_neighbors_), is_transpose_(false){ other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; other.flags_ = nullptr; other.offsets_ = nullptr; out_index_shared_ = other.out_index_shared_; out_neighbors_shared_ = other.out_neighbors_shared_; in_index_shared_ = other.in_index_shared_; in_neighbors_shared_ = other.in_neighbors_shared_; other.out_index_shared_.reset(); other.out_neighbors_shared_.reset(); other.in_index_shared_.reset(); other.in_neighbors_shared_.reset(); other.flags_shared_.reset(); other.offsets_shared_.reset(); //Set this up for getting random neighbors srand(time(NULL)); } ~CSRGraph() { if (!is_transpose_) ReleaseResources(); } CSRGraph& operator=(CSRGraph& other) { if (this != &other) { if (!is_transpose_) ReleaseResources(); directed_ = other.directed_; num_edges_ = other.num_edges_; num_nodes_ = other.num_nodes_; out_index_ = other.out_index_; out_neighbors_ = other.out_neighbors_; in_index_ = other.in_index_; in_neighbors_ = other.in_neighbors_; out_index_shared_ = other.out_index_shared_; out_neighbors_shared_ = other.out_neighbors_shared_; in_index_shared_ = other.in_index_shared_; in_neighbors_shared_ = other.in_neighbors_shared_; //need the following, otherwise would get double free errors /* other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; other.flags_ = nullptr; other.offsets_ = nullptr; */ } return *this; } CSRGraph& operator=(CSRGraph&& other) { if (this != &other) { if (!is_transpose_ ) ReleaseResources(); directed_ = other.directed_; num_edges_ = other.num_edges_; num_nodes_ = other.num_nodes_; out_index_ = other.out_index_; out_neighbors_ = other.out_neighbors_; in_index_ = other.in_index_; in_neighbors_ = other.in_neighbors_; out_index_shared_ = other.out_index_shared_; out_neighbors_shared_ = other.out_neighbors_shared_; in_index_shared_ = other.in_index_shared_; in_neighbors_shared_ = other.in_neighbors_shared_; other.num_edges_ = -1; other.num_nodes_ = -1; other.out_index_ = nullptr; other.out_neighbors_ = nullptr; other.in_index_ = nullptr; other.in_neighbors_ = nullptr; other.flags_ = nullptr; other.offsets_ = nullptr; other.out_index_shared_.reset(); other.out_neighbors_shared_.reset(); other.in_index_shared_.reset(); other.in_neighbors_shared_.reset(); other.flags_shared_.reset(); other.offsets_shared_.reset(); } return *this; } bool directed() const { return directed_; } int64_t num_nodes() const { return num_nodes_; } int64_t num_edges() const { return num_edges_; } int64_t num_edges_directed() const { return directed_ ? num_edges_ : 2*num_edges_; } int64_t out_degree(NodeID_ v) const { return out_index_[v+1] - out_index_[v]; } int64_t in_degree(NodeID_ v) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return in_index_[v+1] - in_index_[v]; } Neighborhood out_neigh(NodeID_ n) const { return Neighborhood(n, out_index_); } Neighborhood in_neigh(NodeID_ n) const { static_assert(MakeInverse, "Graph inversion disabled but reading inverse"); return Neighborhood(n, in_index_); } NodeID_ get_random_out_neigh(NodeID_ n) { int num_nghs = out_degree(n); assert(num_nghs!=0); int rand_index = rand() % num_nghs; return out_index_[n][rand_index]; } NodeID_ get_random_in_neigh(NodeID_ n) { int num_nghs = in_degree(n); assert(num_nghs!=0); int rand_index = rand() % num_nghs; return in_index_[n][rand_index]; } void PrintStats() const { std::cout << "Graph has " << num_nodes_ << " nodes and " << num_edges_ << " "; if (!directed_) std::cout << "un"; std::cout << "directed edges for degree: "; std::cout << num_edges_/num_nodes_ << std::endl; } void PrintTopology() const { for (NodeID_ i=0; i < num_nodes_; i++) { std::cout << i << ": "; for (DestID_ j : out_neigh(i)) { std::cout << j << " "; } std::cout << std::endl; } } static DestID_** GenIndex(const pvector<SGOffset> &offsets, DestID_* neighs) { NodeID_ length = offsets.size(); DestID_** index = new DestID_*[length]; #pragma omp parallel for for (NodeID_ n=0; n < length; n++) index[n] = neighs + offsets[n]; return index; } pvector<SGOffset> VertexOffsets(bool in_graph = false) const { pvector<SGOffset> offsets(num_nodes_+1); for (NodeID_ n=0; n < num_nodes_+1; n++) if (in_graph) offsets[n] = in_index_[n] - in_index_[0]; else offsets[n] = out_index_[n] - out_index_[0]; return offsets; } void SetUpOffsets(bool in_graph = false) { offsets_ = new SGOffset[num_nodes_+1]; offsets_shared_.reset(offsets_); for (NodeID_ n=0; n < num_nodes_+1; n++) if (in_graph) offsets_[n] = in_index_[n] - in_index_[0]; else offsets_[n] = out_index_[n] - out_index_[0]; } Range<NodeID_> vertices() const { return Range<NodeID_>(num_nodes()); } SegmentedGraph<DestID_, NodeID_>* getSegmentedGraph(std::string label, int id) { return label_to_segment[label]->getSegmentedGraph(id); } int getNumSegments(std::string label) { return label_to_segment[label]->numSegments; } void buildPullSegmentedGraphs(std::string label, int numSegments, bool numa_aware=false, std::string path="") { auto graphSegments = new GraphSegments<DestID_,NodeID_>(numSegments, numa_aware); label_to_segment[label] = graphSegments; #ifdef LOADSEG cout << "loading segmented graph from " << path << endl; #pragma omp parallel for num_threads(numSegments) for (int i = 0; i < numSegments; i++) { FILE *in; in = fopen((path + "/" + std::to_string(i)).c_str(), "r"); auto sg = graphSegments->getSegmentedGraph(i); fread((void *) &sg->numVertices, sizeof(sg->numVertices), 1, in); fread((void *) &sg->numEdges, sizeof(sg->numEdges), 1, in); sg->allocate(i); fread((void *) sg->graphId, sizeof(*sg->graphId), sg->numVertices, in); fread((void *) sg->edgeArray, sizeof(*sg->edgeArray), sg->numEdges, in); fread((void *) sg->vertexArray, sizeof(*sg->vertexArray), sg->numVertices + 1, in); fclose(in); } return; #endif int segmentRange = (num_nodes() + numSegments - 1) / numSegments; //Go through the original graph and count the number of target vertices and edges for each segment for (auto d : vertices()){ for (auto s : in_neigh(d)){ int segment_id; if (std::is_same<DestID_, NodeWeight<>>::value) segment_id = static_cast<NodeWeight<>>(s).v/segmentRange; else segment_id = s/segmentRange; graphSegments->getSegmentedGraph(segment_id)->countEdge(d); } } //Allocate each segment graphSegments->allocate(); //Add the edges for each segment for (auto d : vertices()){ for (auto s : in_neigh(d)){ int segment_id; if (std::is_same<DestID_, NodeWeight<>>::value) segment_id = static_cast<NodeWeight<>>(s).v/segmentRange; else segment_id = s/segmentRange; graphSegments->getSegmentedGraph(segment_id)->addEdge(d, s); } } #ifdef STORESEG cout << "output serialized graph segments to " << path << endl; #pragma omp parallel for num_threads(numSegments) for(int i = 0; i < numSegments; i++) { FILE *out = fopen((path + "/" + std::to_string(i)).c_str(), "w"); auto sg = graphSegments->getSegmentedGraph(i); fwrite((void *) &sg->numVertices, sizeof(sg->numVertices), 1, out); fwrite((void *) &sg->numEdges, sizeof(sg->numEdges), 1, out); fwrite((void *) sg->graphId, sizeof(*sg->graphId), sg->numVertices, out); fwrite((void *) sg->edgeArray, sizeof(*sg->edgeArray), sg->numEdges, out); fwrite((void *) sg->vertexArray, sizeof(*sg->vertexArray), sg->numVertices + 1, out); fclose(out); } #endif } private: // Making private so cannot be modified from outside //useful for deduplication int* flags_; SGOffset * offsets_; bool is_transpose_; bool directed_; int64_t num_nodes_; int64_t num_edges_; DestID_** out_index_; DestID_* out_neighbors_; DestID_** in_index_; DestID_* in_neighbors_; public: std::shared_ptr<int> flags_shared_; std::shared_ptr<SGOffset> offsets_shared_; std::shared_ptr<DestID_*> out_index_shared_; std::shared_ptr<DestID_> out_neighbors_shared_; std::shared_ptr<DestID_*> in_index_shared_; std::shared_ptr<DestID_> in_neighbors_shared_; std::map<std::string, GraphSegments<DestID_,NodeID_>*> label_to_segment; DestID_** get_out_index_(void) { return out_index_; } DestID_* get_out_neighbors_(void) { return out_neighbors_; } DestID_** get_in_index_(void) { return in_index_; } DestID_* get_in_neighbors_(void) { return in_neighbors_; } inline int* get_flags_() { return flags_; } inline void set_flags_(int *flags) { flags_ = flags; flags_shared_.reset(flags); } inline SGOffset * get_offsets_(void) { return offsets_; } }; #endif // GRAPH_H_
DRB054-inneronly2-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. */ /* Example with loop-carried data dependence at the outer level loop. The inner level loop can be parallelized. */ int main() { int i,j; int n=100, m=100; double b[n][m]; for(i=0;i<n; i++) for(j=0;j<n; j++) b[i][j]=(double)(i*j); for (i=1;i<n;i++) #pragma omp parallel for schedule(dynamic) for (j=1;j<m;j++) b[i][j]=b[i-1][j-1]; return 0; }
visual-effects.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V V IIIII SSSSS U U AAA L % % V V I SS U U A A L % % V V I SSS U U AAAAA L % % V V I SS U U A A L % % V IIIII SSSSS UUU A A LLLLL % % % % EEEEE FFFFF FFFFF EEEEE CCCC TTTTT SSSSS % % E F F E C T SS % % EEE FFF FFF EEE C T SSS % % E F F E C T SS % % EEEEE F F EEEEE CCCC T SSSSS % % % % % % MagickCore Image Special Effects Methods % % % % Software Design % % Cristy % % October 1996 % % % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/accelerate-private.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.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/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" #include "MagickCore/visual-effects.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d d N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AddNoiseImage() adds random noise to the image. % % The format of the AddNoiseImage method is: % % Image *AddNoiseImage(const Image *image,const NoiseType noise_type, % const double attenuate,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o noise_type: The type of noise: Uniform, Gaussian, Multiplicative, % Impulse, Laplacian, or Poisson. % % o attenuate: attenuate the random distribution. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AddNoiseImage(const Image *image,const NoiseType noise_type, const double attenuate,ExceptionInfo *exception) { #define AddNoiseImageTag "AddNoise/Image" CacheView *image_view, *noise_view; Image *noise_image; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Initialize noise 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 defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateAddNoiseImage(image,noise_type,attenuate,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } /* Add noise in each row. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireVirtualCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,noise_image,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait noise_traits=GetPixelChannelTraits(noise_image,channel); if ((traits == UndefinedPixelTrait) || (noise_traits == UndefinedPixelTrait)) continue; if ((noise_traits & CopyPixelTrait) != 0) { SetPixelChannel(noise_image,channel,p[i],q); continue; } SetPixelChannel(noise_image,channel,ClampToQuantum( GenerateDifferentialNoise(random_info[id],p[i],noise_type,attenuate)), q); } p+=GetPixelChannels(image); q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,AddNoiseImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l u e S h i f t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlueShiftImage() mutes the colors of the image to simulate a scene at % nighttime in the moonlight. % % The format of the BlueShiftImage method is: % % Image *BlueShiftImage(const Image *image,const double factor, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o factor: the shift factor. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *BlueShiftImage(const Image *image,const double factor, ExceptionInfo *exception) { #define BlueShiftImageTag "BlueShift/Image" CacheView *image_view, *shift_view; Image *shift_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate blue shift 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); shift_image=CloneImage(image,0,0,MagickTrue,exception); if (shift_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(shift_image,DirectClass,exception) == MagickFalse) { shift_image=DestroyImage(shift_image); return((Image *) NULL); } /* Blue-shift DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); shift_view=AcquireAuthenticCacheView(shift_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,shift_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; PixelInfo pixel; Quantum quantum; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(shift_view,0,y,shift_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) < quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) < quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(GetPixelRed(image,p)+factor*quantum); pixel.green=0.5*(GetPixelGreen(image,p)+factor*quantum); pixel.blue=0.5*(GetPixelBlue(image,p)+factor*quantum); quantum=GetPixelRed(image,p); if (GetPixelGreen(image,p) > quantum) quantum=GetPixelGreen(image,p); if (GetPixelBlue(image,p) > quantum) quantum=GetPixelBlue(image,p); pixel.red=0.5*(pixel.red+factor*quantum); pixel.green=0.5*(pixel.green+factor*quantum); pixel.blue=0.5*(pixel.blue+factor*quantum); SetPixelRed(shift_image,ClampToQuantum(pixel.red),q); SetPixelGreen(shift_image,ClampToQuantum(pixel.green),q); SetPixelBlue(shift_image,ClampToQuantum(pixel.blue),q); p+=GetPixelChannels(image); q+=GetPixelChannels(shift_image); } sync=SyncCacheViewAuthenticPixels(shift_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,BlueShiftImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); shift_view=DestroyCacheView(shift_view); if (status == MagickFalse) shift_image=DestroyImage(shift_image); return(shift_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h a r c o a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CharcoalImage() creates a new image that is a copy of an existing one with % the edge highlighted. It allocates the memory necessary for the new Image % structure and returns a pointer to the new image. % % The format of the CharcoalImage method is: % % Image *CharcoalImage(const Image *image,const double radius, % const double sigma,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CharcoalImage(const Image *image,const double radius, const double sigma,ExceptionInfo *exception) { Image *charcoal_image, *edge_image; MagickBooleanType status; 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); edge_image=EdgeImage(image,radius,exception); if (edge_image == (Image *) NULL) return((Image *) NULL); edge_image->alpha_trait=UndefinedPixelTrait; charcoal_image=(Image *) NULL; status=ClampImage(edge_image,exception); if (status != MagickFalse) charcoal_image=BlurImage(edge_image,radius,sigma,exception); edge_image=DestroyImage(edge_image); if (charcoal_image == (Image *) NULL) return((Image *) NULL); status=NormalizeImage(charcoal_image,exception); if (status != MagickFalse) status=NegateImage(charcoal_image,MagickFalse,exception); if (status != MagickFalse) status=GrayscaleImage(charcoal_image,image->intensity,exception); if (status == MagickFalse) charcoal_image=DestroyImage(charcoal_image); return(charcoal_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorizeImage() blends the fill color with each pixel in the image. % A percentage blend is specified with opacity. Control the application % of different color components by specifying a different percentage for % each component (e.g. 90/100/10 is 90% red, 100% green, and 10% blue). % % The format of the ColorizeImage method is: % % Image *ColorizeImage(const Image *image,const char *blend, % const PixelInfo *colorize,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A character string indicating the level of blending as a % percentage. % % o colorize: A color value. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ColorizeImage(const Image *image,const char *blend, const PixelInfo *colorize,ExceptionInfo *exception) { #define ColorizeImageTag "Colorize/Image" #define Colorize(pixel,blend_percentage,colorize) \ (((pixel)*(100.0-(blend_percentage))+(colorize)*(blend_percentage))/100.0) CacheView *image_view; GeometryInfo geometry_info; Image *colorize_image; MagickBooleanType status; MagickOffsetType progress; MagickStatusType flags; PixelInfo blend_percentage; ssize_t y; /* Allocate colorized 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); colorize_image=CloneImage(image,0,0,MagickTrue,exception); if (colorize_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(colorize_image,DirectClass,exception) == MagickFalse) { colorize_image=DestroyImage(colorize_image); return((Image *) NULL); } if ((IsGrayColorspace(colorize_image->colorspace) != MagickFalse) || (IsPixelInfoGray(colorize) != MagickFalse)) (void) SetImageColorspace(colorize_image,sRGBColorspace,exception); if ((colorize_image->alpha_trait == UndefinedPixelTrait) && (colorize->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlpha(colorize_image,OpaqueAlpha,exception); if (blend == (const char *) NULL) return(colorize_image); GetPixelInfo(colorize_image,&blend_percentage); flags=ParseGeometry(blend,&geometry_info); blend_percentage.red=geometry_info.rho; blend_percentage.green=geometry_info.rho; blend_percentage.blue=geometry_info.rho; blend_percentage.black=geometry_info.rho; blend_percentage.alpha=(MagickRealType) TransparentAlpha; if ((flags & SigmaValue) != 0) blend_percentage.green=geometry_info.sigma; if ((flags & XiValue) != 0) blend_percentage.blue=geometry_info.xi; if ((flags & PsiValue) != 0) blend_percentage.alpha=geometry_info.psi; if (blend_percentage.colorspace == CMYKColorspace) { if ((flags & PsiValue) != 0) blend_percentage.black=geometry_info.psi; if ((flags & ChiValue) != 0) blend_percentage.alpha=geometry_info.chi; } /* Colorize DirectClass image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(colorize_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(colorize_image,colorize_image,colorize_image->rows,1) #endif for (y=0; y < (ssize_t) colorize_image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,colorize_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) colorize_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(colorize_image); i++) { PixelTrait traits = GetPixelChannelTraits(colorize_image, (PixelChannel) i); if (traits == UndefinedPixelTrait) continue; if ((traits & CopyPixelTrait) != 0) continue; SetPixelChannel(colorize_image,(PixelChannel) i,ClampToQuantum( Colorize(q[i],GetPixelInfoChannel(&blend_percentage,(PixelChannel) i), GetPixelInfoChannel(colorize,(PixelChannel) i))),q); } q+=GetPixelChannels(colorize_image); } 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 atomic #endif progress++; proceed=SetImageProgress(image,ColorizeImageTag,progress, colorize_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); if (status == MagickFalse) colorize_image=DestroyImage(colorize_image); return(colorize_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o l o r M a t r i x I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ColorMatrixImage() applies color transformation to an image. This method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the ColorMatrixImage method is: % % Image *ColorMatrixImage(const Image *image, % const KernelInfo *color_matrix,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o color_matrix: the color matrix. % % o exception: return any errors or warnings in this structure. % */ /* FUTURE: modify to make use of a MagickMatrix Mutliply function That should be provided in "matrix.c" (ASIDE: actually distorts should do this too but currently doesn't) */ MagickExport Image *ColorMatrixImage(const Image *image, const KernelInfo *color_matrix,ExceptionInfo *exception) { #define ColorMatrixImageTag "ColorMatrix/Image" CacheView *color_view, *image_view; double ColorMatrix[6][6] = { { 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 1.0, 0.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 1.0, 0.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 1.0, 0.0 }, { 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 } }; Image *color_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t u, v, y; /* Map given color_matrix, into a 6x6 matrix RGBKA and a constant */ 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); i=0; for (v=0; v < (ssize_t) color_matrix->height; v++) for (u=0; u < (ssize_t) color_matrix->width; u++) { if ((v < 6) && (u < 6)) ColorMatrix[v][u]=color_matrix->values[i]; i++; } /* Initialize color image. */ color_image=CloneImage(image,0,0,MagickTrue,exception); if (color_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(color_image,DirectClass,exception) == MagickFalse) { color_image=DestroyImage(color_image); return((Image *) NULL); } if (image->debug != MagickFalse) { char format[MagickPathExtent], *message; (void) LogMagickEvent(TransformEvent,GetMagickModule(), " ColorMatrix image with color matrix:"); message=AcquireString(""); for (v=0; v < 6; v++) { *message='\0'; (void) FormatLocaleString(format,MagickPathExtent,"%.20g: ",(double) v); (void) ConcatenateString(&message,format); for (u=0; u < 6; u++) { (void) FormatLocaleString(format,MagickPathExtent,"%+f ", ColorMatrix[v][u]); (void) ConcatenateString(&message,format); } (void) LogMagickEvent(TransformEvent,GetMagickModule(),"%s",message); } message=DestroyString(message); } /* Apply the ColorMatrix to image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); color_view=AcquireAuthenticCacheView(color_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,color_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { PixelInfo pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(color_view,0,y,color_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } GetPixelInfo(image,&pixel); for (x=0; x < (ssize_t) image->columns; x++) { ssize_t v; size_t height; GetPixelInfoPixel(image,p,&pixel); height=color_matrix->height > 6 ? 6UL : color_matrix->height; for (v=0; v < (ssize_t) height; v++) { double sum; sum=ColorMatrix[v][0]*GetPixelRed(image,p)+ColorMatrix[v][1]* GetPixelGreen(image,p)+ColorMatrix[v][2]*GetPixelBlue(image,p); if (image->colorspace == CMYKColorspace) sum+=ColorMatrix[v][3]*GetPixelBlack(image,p); if (image->alpha_trait != UndefinedPixelTrait) sum+=ColorMatrix[v][4]*GetPixelAlpha(image,p); sum+=QuantumRange*ColorMatrix[v][5]; switch (v) { case 0: pixel.red=sum; break; case 1: pixel.green=sum; break; case 2: pixel.blue=sum; break; case 3: pixel.black=sum; break; case 4: pixel.alpha=sum; break; default: break; } } SetPixelViaPixelInfo(color_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(color_image); } if (SyncCacheViewAuthenticPixels(color_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,ColorMatrixImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } color_view=DestroyCacheView(color_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) color_image=DestroyImage(color_image); return(color_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p l o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImplodeImage() creates a new image that is a copy of an existing % one with the image pixels "implode" by the specified percentage. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ImplodeImage method is: % % Image *ImplodeImage(const Image *image,const double amount, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o implode_image: Method ImplodeImage returns a pointer to the image % after it is implode. A null image is returned if there is a memory % shortage. % % o image: the image. % % o amount: Define the extent of the implosion. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ImplodeImage(const Image *image,const double amount, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define ImplodeImageTag "Implode/Image" CacheView *canvas_view, *implode_view, *interpolate_view; double radius; Image *canvas_image, *implode_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize implode image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlphaChannel(canvas_image,OpaqueAlphaChannel,exception); implode_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (implode_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(implode_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); implode_image=DestroyImage(implode_image); return((Image *) NULL); } /* Compute scaling factor. */ scale.x=1.0; scale.y=1.0; center.x=0.5*canvas_image->columns; center.y=0.5*canvas_image->rows; radius=center.x; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns*PerceptibleReciprocal((double) canvas_image->rows); else if (canvas_image->columns < canvas_image->rows) { scale.x=(double) canvas_image->rows*PerceptibleReciprocal((double) canvas_image->columns); radius=center.y; } /* Implode image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(canvas_image,exception); implode_view=AcquireAuthenticCacheView(implode_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,implode_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(implode_view,0,y,implode_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { ssize_t i; /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait implode_traits = GetPixelChannelTraits(implode_image, channel); if ((traits == UndefinedPixelTrait) || (implode_traits == UndefinedPixelTrait)) continue; SetPixelChannel(implode_image,channel,p[i],q); } else { double factor; /* Implode the pixel. */ factor=1.0; if (distance > 0.0) factor=pow(sin(MagickPI*sqrt((double) distance)*PerceptibleReciprocal(radius)/2),-amount); status=InterpolatePixelChannels(canvas_image,interpolate_view, implode_image,method,(double) (factor*delta.x*PerceptibleReciprocal(scale.x)+center.x), (double) (factor*delta.y*PerceptibleReciprocal(scale.y)+center.y),q,exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(implode_image); } if (SyncCacheViewAuthenticPixels(implode_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,ImplodeImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } implode_view=DestroyCacheView(implode_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) implode_image=DestroyImage(implode_image); return(implode_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M o r p h I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The MorphImages() method requires a minimum of two images. The first % image is transformed into the second by a number of intervening images % as specified by frames. % % The format of the MorphImage method is: % % Image *MorphImages(const Image *image,const size_t number_frames, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_frames: Define the number of in-between image to generate. % The more in-between frames, the smoother the morph. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *MorphImages(const Image *image,const size_t number_frames, ExceptionInfo *exception) { #define MorphImageTag "Morph/Image" double alpha, beta; Image *morph_image, *morph_images; MagickBooleanType status; MagickOffsetType scene; const Image *next; ssize_t n; ssize_t y; /* Clone first frame in sequence. */ 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); morph_images=CloneImage(image,0,0,MagickTrue,exception); if (morph_images == (Image *) NULL) return((Image *) NULL); if (GetNextImageInList(image) == (Image *) NULL) { /* Morph single image. */ for (n=1; n < (ssize_t) number_frames; n++) { morph_image=CloneImage(image,0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,(MagickOffsetType) n, number_frames); if (proceed == MagickFalse) status=MagickFalse; } } return(GetFirstImageInList(morph_images)); } /* Morph image sequence. */ status=MagickTrue; scene=0; next=image; for ( ; GetNextImageInList(next) != (Image *) NULL; next=GetNextImageInList(next)) { for (n=0; n < (ssize_t) number_frames; n++) { CacheView *image_view, *morph_view; beta=(double) (n+1.0)/(double) (number_frames+1.0); alpha=1.0-beta; morph_image=ResizeImage(next,(size_t) (alpha*next->columns+beta* GetNextImageInList(next)->columns+0.5),(size_t) (alpha*next->rows+beta* GetNextImageInList(next)->rows+0.5),next->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } status=SetImageStorageClass(morph_image,DirectClass,exception); if (status == MagickFalse) { morph_image=DestroyImage(morph_image); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); morph_image=ResizeImage(GetNextImageInList(next),morph_images->columns, morph_images->rows,GetNextImageInList(next)->filter,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } image_view=AcquireVirtualCacheView(morph_image,exception); morph_view=AcquireAuthenticCacheView(morph_images,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(morph_image,morph_image,morph_image->rows,1) #endif for (y=0; y < (ssize_t) morph_images->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,morph_image->columns,1, exception); q=GetCacheViewAuthenticPixels(morph_view,0,y,morph_images->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) morph_images->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(morph_image); i++) { PixelChannel channel = GetPixelChannelChannel(morph_image,i); PixelTrait traits = GetPixelChannelTraits(morph_image,channel); PixelTrait morph_traits=GetPixelChannelTraits(morph_images,channel); if ((traits == UndefinedPixelTrait) || (morph_traits == UndefinedPixelTrait)) continue; if ((morph_traits & CopyPixelTrait) != 0) { SetPixelChannel(morph_image,channel,p[i],q); continue; } SetPixelChannel(morph_image,channel,ClampToQuantum(alpha* GetPixelChannel(morph_images,channel,q)+beta*p[i]),q); } p+=GetPixelChannels(morph_image); q+=GetPixelChannels(morph_images); } sync=SyncCacheViewAuthenticPixels(morph_view,exception); if (sync == MagickFalse) status=MagickFalse; } morph_view=DestroyCacheView(morph_view); image_view=DestroyCacheView(image_view); morph_image=DestroyImage(morph_image); } if (n < (ssize_t) number_frames) break; /* Clone last frame in sequence. */ morph_image=CloneImage(GetNextImageInList(next),0,0,MagickTrue,exception); if (morph_image == (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } AppendImageToList(&morph_images,morph_image); morph_images=GetLastImageInList(morph_images); if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,MorphImageTag,scene, GetImageListLength(image)); if (proceed == MagickFalse) status=MagickFalse; } scene++; } if (GetNextImageInList(next) != (Image *) NULL) { morph_images=DestroyImageList(morph_images); return((Image *) NULL); } return(GetFirstImageInList(morph_images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P l a s m a I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PlasmaImage() initializes an image with plasma fractal values. The image % must be initialized with a base color and the random number generator % seeded before this method is called. % % The format of the PlasmaImage method is: % % MagickBooleanType PlasmaImage(Image *image,const SegmentInfo *segment, % size_t attenuate,size_t depth,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o segment: Define the region to apply plasma fractals values. % % o attenuate: Define the plasma attenuation factor. % % o depth: Limit the plasma recursion depth. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum PlasmaPixel(RandomInfo *magick_restrict random_info, const double pixel,const double noise) { MagickRealType plasma; plasma=pixel+noise*GetPseudoRandomValue(random_info)-noise/2.0; return(ClampToQuantum(plasma)); } static MagickBooleanType PlasmaImageProxy(Image *image,CacheView *image_view, CacheView *u_view,CacheView *v_view,RandomInfo *magick_restrict random_info, const SegmentInfo *magick_restrict segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { double plasma; MagickStatusType status; const Quantum *magick_restrict u, *magick_restrict v; Quantum *magick_restrict q; ssize_t i; ssize_t x, x_mid, y, y_mid; if ((fabs(segment->x2-segment->x1) < MagickEpsilon) && (fabs(segment->y2-segment->y1) < MagickEpsilon)) return(MagickTrue); if (depth != 0) { SegmentInfo local_info; /* Divide the area into quadrants and recurse. */ depth--; attenuate++; x_mid=CastDoubleToLong(ceil((segment->x1+segment->x2)/2-0.5)); y_mid=CastDoubleToLong(ceil((segment->y1+segment->y2)/2-0.5)); local_info=(*segment); local_info.x2=(double) x_mid; local_info.y2=(double) y_mid; status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.y1=(double) y_mid; local_info.x2=(double) x_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y2=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); local_info=(*segment); local_info.x1=(double) x_mid; local_info.y1=(double) y_mid; status&=PlasmaImageProxy(image,image_view,u_view,v_view,random_info, &local_info,attenuate,depth,exception); return(status == 0 ? MagickFalse : MagickTrue); } x_mid=CastDoubleToLong(ceil((segment->x1+segment->x2)/2-0.5)); y_mid=CastDoubleToLong(ceil((segment->y1+segment->y2)/2-0.5)); if ((fabs(segment->x1-x_mid) < MagickEpsilon) && (fabs(segment->x2-x_mid) < MagickEpsilon) && (fabs(segment->y1-y_mid) < MagickEpsilon) && (fabs(segment->y2-y_mid) < MagickEpsilon)) return(MagickFalse); /* Average pixels and apply plasma. */ status=MagickTrue; plasma=(double) QuantumRange/(2.0*attenuate); if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->x2-x_mid) >= MagickEpsilon)) { /* Left pixel. */ x=CastDoubleToLong(ceil(segment->x1-0.5)); u=GetCacheViewVirtualPixels(u_view,x,CastDoubleToLong(ceil( segment->y1-0.5)),1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,CastDoubleToLong(ceil( segment->y2-0.5)),1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); if (fabs(segment->x1-segment->x2) >= MagickEpsilon) { /* Right pixel. */ x=CastDoubleToLong(ceil(segment->x2-0.5)); u=GetCacheViewVirtualPixels(u_view,x,CastDoubleToLong(ceil( segment->y1-0.5)),1,1,exception); v=GetCacheViewVirtualPixels(v_view,x,CastDoubleToLong(ceil( segment->y2-0.5)),1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->y1-y_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { if ((fabs(segment->x1-x_mid) >= MagickEpsilon) || (fabs(segment->y2-y_mid) >= MagickEpsilon)) { /* Bottom pixel. */ y=CastDoubleToLong(ceil(segment->y2-0.5)); u=GetCacheViewVirtualPixels(u_view,CastDoubleToLong(ceil( segment->x1-0.5)),y,1,1,exception); v=GetCacheViewVirtualPixels(v_view,CastDoubleToLong(ceil( segment->x2-0.5)),y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if (fabs(segment->y1-segment->y2) >= MagickEpsilon) { /* Top pixel. */ y=CastDoubleToLong(ceil(segment->y1-0.5)); u=GetCacheViewVirtualPixels(u_view,CastDoubleToLong(ceil( segment->x1-0.5)),y,1,1,exception); v=GetCacheViewVirtualPixels(v_view,CastDoubleToLong(ceil( segment->x2-0.5)),y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } } if ((fabs(segment->x1-segment->x2) >= MagickEpsilon) || (fabs(segment->y1-segment->y2) >= MagickEpsilon)) { /* Middle pixel. */ x=CastDoubleToLong(ceil(segment->x1-0.5)); y=CastDoubleToLong(ceil(segment->y1-0.5)); u=GetCacheViewVirtualPixels(u_view,x,y,1,1,exception); x=CastDoubleToLong(ceil(segment->x2-0.5)); y=CastDoubleToLong(ceil(segment->y2-0.5)); v=GetCacheViewVirtualPixels(v_view,x,y,1,1,exception); q=QueueCacheViewAuthenticPixels(image_view,x_mid,y_mid,1,1,exception); if ((u == (const Quantum *) NULL) || (v == (const Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickTrue); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=PlasmaPixel(random_info,((double) u[i]+v[i])/2.0,plasma); } status=SyncCacheViewAuthenticPixels(image_view,exception); } if ((fabs(segment->x2-segment->x1) < 3.0) && (fabs(segment->y2-segment->y1) < 3.0)) return(status == 0 ? MagickFalse : MagickTrue); return(MagickFalse); } MagickExport MagickBooleanType PlasmaImage(Image *image, const SegmentInfo *segment,size_t attenuate,size_t depth, ExceptionInfo *exception) { CacheView *image_view, *u_view, *v_view; MagickBooleanType status; RandomInfo *random_info; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); u_view=AcquireVirtualCacheView(image,exception); v_view=AcquireVirtualCacheView(image,exception); random_info=AcquireRandomInfo(); status=PlasmaImageProxy(image,image_view,u_view,v_view,random_info,segment, attenuate,depth,exception); random_info=DestroyRandomInfo(random_info); v_view=DestroyCacheView(v_view); u_view=DestroyCacheView(u_view); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l a r o i d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolaroidImage() simulates a Polaroid picture. % % The format of the PolaroidImage method is: % % Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, % const char *caption,const double angle, % const PixelInterpolateMethod method,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o draw_info: the draw info. % % o caption: the Polaroid caption. % % o angle: Apply the effect along this angle. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolaroidImage(const Image *image,const DrawInfo *draw_info, const char *caption,const double angle,const PixelInterpolateMethod method, ExceptionInfo *exception) { Image *bend_image, *caption_image, *flop_image, *picture_image, *polaroid_image, *rotate_image, *trim_image; size_t height; ssize_t quantum; /* Simulate a Polaroid picture. */ 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); quantum=(ssize_t) MagickMax(MagickMax((double) image->columns,(double) image->rows)/25.0,10.0); height=image->rows+2*quantum; caption_image=(Image *) NULL; if (caption != (const char *) NULL) { char *text; /* Generate caption image. */ caption_image=CloneImage(image,image->columns,1,MagickTrue,exception); if (caption_image == (Image *) NULL) return((Image *) NULL); text=InterpretImageProperties((ImageInfo *) NULL,(Image *) image,caption, exception); if (text != (char *) NULL) { char geometry[MagickPathExtent]; DrawInfo *annotate_info; MagickBooleanType status; ssize_t count; TypeMetric metrics; annotate_info=CloneDrawInfo((const ImageInfo *) NULL,draw_info); (void) CloneString(&annotate_info->text,text); count=FormatMagickCaption(caption_image,annotate_info,MagickTrue, &metrics,&text,exception); status=SetImageExtent(caption_image,image->columns,(size_t) ((count+1)*(metrics.ascent-metrics.descent)+0.5),exception); if (status == MagickFalse) caption_image=DestroyImage(caption_image); else { caption_image->background_color=image->border_color; (void) SetImageBackgroundColor(caption_image,exception); (void) CloneString(&annotate_info->text,text); (void) FormatLocaleString(geometry,MagickPathExtent,"+0+%.20g", metrics.ascent); if (annotate_info->gravity == UndefinedGravity) (void) CloneString(&annotate_info->geometry,AcquireString( geometry)); (void) AnnotateImage(caption_image,annotate_info,exception); height+=caption_image->rows; } annotate_info=DestroyDrawInfo(annotate_info); text=DestroyString(text); } } picture_image=CloneImage(image,image->columns+2*quantum,height,MagickTrue, exception); if (picture_image == (Image *) NULL) { if (caption_image != (Image *) NULL) caption_image=DestroyImage(caption_image); return((Image *) NULL); } picture_image->background_color=image->border_color; (void) SetImageBackgroundColor(picture_image,exception); (void) CompositeImage(picture_image,image,OverCompositeOp,MagickTrue,quantum, quantum,exception); if (caption_image != (Image *) NULL) { (void) CompositeImage(picture_image,caption_image,OverCompositeOp, MagickTrue,quantum,(ssize_t) (image->rows+3*quantum/2),exception); caption_image=DestroyImage(caption_image); } (void) QueryColorCompliance("none",AllCompliance, &picture_image->background_color,exception); (void) SetImageAlphaChannel(picture_image,OpaqueAlphaChannel,exception); rotate_image=RotateImage(picture_image,90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; bend_image=WaveImage(picture_image,0.01*picture_image->rows,2.0* picture_image->columns,method,exception); picture_image=DestroyImage(picture_image); if (bend_image == (Image *) NULL) return((Image *) NULL); picture_image=bend_image; rotate_image=RotateImage(picture_image,-90.0,exception); picture_image=DestroyImage(picture_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); picture_image=rotate_image; picture_image->background_color=image->background_color; polaroid_image=ShadowImage(picture_image,80.0,2.0,quantum/3,quantum/3, exception); if (polaroid_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } flop_image=FlopImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (flop_image == (Image *) NULL) { picture_image=DestroyImage(picture_image); return(picture_image); } polaroid_image=flop_image; (void) CompositeImage(polaroid_image,picture_image,OverCompositeOp, MagickTrue,(ssize_t) (-0.01*picture_image->columns/2.0),0L,exception); picture_image=DestroyImage(picture_image); (void) QueryColorCompliance("none",AllCompliance, &polaroid_image->background_color,exception); rotate_image=RotateImage(polaroid_image,angle,exception); polaroid_image=DestroyImage(polaroid_image); if (rotate_image == (Image *) NULL) return((Image *) NULL); polaroid_image=rotate_image; trim_image=TrimImage(polaroid_image,exception); polaroid_image=DestroyImage(polaroid_image); if (trim_image == (Image *) NULL) return((Image *) NULL); polaroid_image=trim_image; return(polaroid_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e p i a T o n e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSepiaToneImage() applies a special effect to the image, similar to the % effect achieved in a photo darkroom by sepia toning. Threshold ranges from % 0 to QuantumRange and is a measure of the extent of the sepia toning. A % threshold of 80% is a good starting point for a reasonable tone. % % The format of the SepiaToneImage method is: % % Image *SepiaToneImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: the tone threshold. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SepiaToneImage(const Image *image,const double threshold, ExceptionInfo *exception) { #define SepiaToneImageTag "SepiaTone/Image" CacheView *image_view, *sepia_view; Image *sepia_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Initialize sepia-toned 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); sepia_image=CloneImage(image,0,0,MagickTrue,exception); if (sepia_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(sepia_image,DirectClass,exception) == MagickFalse) { sepia_image=DestroyImage(sepia_image); return((Image *) NULL); } /* Tone each row of the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); sepia_view=AcquireAuthenticCacheView(sepia_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,sepia_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(sepia_view,0,y,sepia_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double intensity, tone; intensity=GetPixelIntensity(image,p); tone=intensity > threshold ? (double) QuantumRange : intensity+ (double) QuantumRange-threshold; SetPixelRed(sepia_image,ClampToQuantum(tone),q); tone=intensity > (7.0*threshold/6.0) ? (double) QuantumRange : intensity+(double) QuantumRange-7.0*threshold/6.0; SetPixelGreen(sepia_image,ClampToQuantum(tone),q); tone=intensity < (threshold/6.0) ? 0 : intensity-threshold/6.0; SetPixelBlue(sepia_image,ClampToQuantum(tone),q); tone=threshold/7.0; if ((double) GetPixelGreen(image,q) < tone) SetPixelGreen(sepia_image,ClampToQuantum(tone),q); if ((double) GetPixelBlue(image,q) < tone) SetPixelBlue(sepia_image,ClampToQuantum(tone),q); SetPixelAlpha(sepia_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(sepia_image); } if (SyncCacheViewAuthenticPixels(sepia_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,SepiaToneImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } sepia_view=DestroyCacheView(sepia_view); image_view=DestroyCacheView(image_view); (void) NormalizeImage(sepia_image,exception); (void) ContrastImage(sepia_image,MagickTrue,exception); if (status == MagickFalse) sepia_image=DestroyImage(sepia_image); return(sepia_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a d o w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShadowImage() simulates a shadow from the specified image and returns it. % % The format of the ShadowImage method is: % % Image *ShadowImage(const Image *image,const double alpha, % const double sigma,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o alpha: percentage transparency. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x_offset: the shadow x-offset. % % o y_offset: the shadow y-offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShadowImage(const Image *image,const double alpha, const double sigma,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define ShadowImageTag "Shadow/Image" CacheView *image_view; ChannelType channel_mask; Image *border_image, *clone_image, *shadow_image; MagickBooleanType status; PixelInfo background_color; RectangleInfo border_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(clone_image,sRGBColorspace,exception); (void) SetImageVirtualPixelMethod(clone_image,EdgeVirtualPixelMethod, exception); border_info.width=(size_t) floor(2.0*sigma+0.5); border_info.height=(size_t) floor(2.0*sigma+0.5); border_info.x=0; border_info.y=0; (void) QueryColorCompliance("none",AllCompliance,&clone_image->border_color, exception); clone_image->alpha_trait=BlendPixelTrait; border_image=BorderImage(clone_image,&border_info,OverCompositeOp,exception); clone_image=DestroyImage(clone_image); if (border_image == (Image *) NULL) return((Image *) NULL); if (border_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(border_image,OpaqueAlphaChannel,exception); /* Shadow image. */ status=MagickTrue; background_color=border_image->background_color; background_color.alpha_trait=BlendPixelTrait; image_view=AcquireAuthenticCacheView(border_image,exception); for (y=0; y < (ssize_t) border_image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(image_view,0,y,border_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) border_image->columns; x++) { if (border_image->alpha_trait != UndefinedPixelTrait) background_color.alpha=GetPixelAlpha(border_image,q)*alpha/100.0; SetPixelViaPixelInfo(border_image,&background_color,q); q+=GetPixelChannels(border_image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); if (status == MagickFalse) { border_image=DestroyImage(border_image); return((Image *) NULL); } channel_mask=SetImageChannelMask(border_image,AlphaChannel); shadow_image=BlurImage(border_image,0.0,sigma,exception); border_image=DestroyImage(border_image); if (shadow_image == (Image *) NULL) return((Image *) NULL); (void) SetPixelChannelMask(shadow_image,channel_mask); if (shadow_image->page.width == 0) shadow_image->page.width=shadow_image->columns; if (shadow_image->page.height == 0) shadow_image->page.height=shadow_image->rows; shadow_image->page.width+=x_offset-(ssize_t) border_info.width; shadow_image->page.height+=y_offset-(ssize_t) border_info.height; shadow_image->page.x+=x_offset-(ssize_t) border_info.width; shadow_image->page.y+=y_offset-(ssize_t) border_info.height; return(shadow_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S k e t c h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SketchImage() simulates a pencil sketch. We convolve the image with a % Gaussian operator of the given radius and standard deviation (sigma). For % reasonable results, radius should be larger than sigma. Use a radius of 0 % and SketchImage() selects a suitable radius for you. Angle gives the angle % of the sketch. % % The format of the SketchImage method is: % % Image *SketchImage(const Image *image,const double radius, % const double sigma,const double angle,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the Gaussian, in pixels, not counting the % center pixel. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o angle: apply the effect along this angle. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SketchImage(const Image *image,const double radius, const double sigma,const double angle,ExceptionInfo *exception) { CacheView *random_view; Image *blend_image, *blur_image, *dodge_image, *random_image, *sketch_image; MagickBooleanType status; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif /* Sketch image. */ random_image=CloneImage(image,image->columns << 1,image->rows << 1, MagickTrue,exception); if (random_image == (Image *) NULL) return((Image *) NULL); status=MagickTrue; random_info=AcquireRandomInfoThreadSet(); random_view=AcquireAuthenticCacheView(random_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(random_image,random_image,random_image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) random_image->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(random_view,0,y,random_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) random_image->columns; x++) { double value; ssize_t i; value=GetPseudoRandomValue(random_info[id]); for (i=0; i < (ssize_t) GetPixelChannels(random_image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; q[i]=ClampToQuantum(QuantumRange*value); } q+=GetPixelChannels(random_image); } if (SyncCacheViewAuthenticPixels(random_view,exception) == MagickFalse) status=MagickFalse; } random_view=DestroyCacheView(random_view); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) { random_image=DestroyImage(random_image); return(random_image); } blur_image=MotionBlurImage(random_image,radius,sigma,angle,exception); random_image=DestroyImage(random_image); if (blur_image == (Image *) NULL) return((Image *) NULL); dodge_image=EdgeImage(blur_image,radius,exception); blur_image=DestroyImage(blur_image); if (dodge_image == (Image *) NULL) return((Image *) NULL); status=ClampImage(dodge_image,exception); if (status != MagickFalse) status=NormalizeImage(dodge_image,exception); if (status != MagickFalse) status=NegateImage(dodge_image,MagickFalse,exception); if (status != MagickFalse) status=TransformImage(&dodge_image,(char *) NULL,"50%",exception); sketch_image=CloneImage(image,0,0,MagickTrue,exception); if (sketch_image == (Image *) NULL) { dodge_image=DestroyImage(dodge_image); return((Image *) NULL); } (void) CompositeImage(sketch_image,dodge_image,ColorDodgeCompositeOp, MagickTrue,0,0,exception); dodge_image=DestroyImage(dodge_image); blend_image=CloneImage(image,0,0,MagickTrue,exception); if (blend_image == (Image *) NULL) { sketch_image=DestroyImage(sketch_image); return((Image *) NULL); } if (blend_image->alpha_trait != BlendPixelTrait) (void) SetImageAlpha(blend_image,TransparentAlpha,exception); (void) SetImageArtifact(blend_image,"compose:args","20x80"); (void) CompositeImage(sketch_image,blend_image,BlendCompositeOp,MagickTrue, 0,0,exception); blend_image=DestroyImage(blend_image); return(sketch_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o l a r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SolarizeImage() applies a special effect to the image, similar to the effect % achieved in a photo darkroom by selectively exposing areas of photo % sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a % measure of the extent of the solarization. % % The format of the SolarizeImage method is: % % MagickBooleanType SolarizeImage(Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: Define the extent of the solarization. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SolarizeImage(Image *image, const double threshold,ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace,exception); if (image->storage_class == PseudoClass) { ssize_t i; /* Solarize colormap. */ for (i=0; i < (ssize_t) image->colors; i++) { if ((double) image->colormap[i].red > threshold) image->colormap[i].red=QuantumRange-image->colormap[i].red; if ((double) image->colormap[i].green > threshold) image->colormap[i].green=QuantumRange-image->colormap[i].green; if ((double) image->colormap[i].blue > threshold) image->colormap[i].blue=QuantumRange-image->colormap[i].blue; } return(SyncImage(image,exception)); } /* Solarize image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; if ((double) q[i] > threshold) q[i]=QuantumRange-q[i]; } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e g a n o I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SteganoImage() hides a digital watermark within the image. Recover % the hidden watermark later to prove that the authenticity of an image. % Offset defines the start position within the image to hide the watermark. % % The format of the SteganoImage method is: % % Image *SteganoImage(const Image *image,Image *watermark, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o watermark: the watermark image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SteganoImage(const Image *image,const Image *watermark, ExceptionInfo *exception) { #define GetBit(alpha,i) ((((size_t) (alpha) >> (size_t) (i)) & 0x01) != 0) #define SetBit(alpha,i,set) (Quantum) ((set) != 0 ? (size_t) (alpha) \ | (one << (size_t) (i)) : (size_t) (alpha) & ~(one << (size_t) (i))) #define SteganoImageTag "Stegano/Image" CacheView *stegano_view, *watermark_view; Image *stegano_image; int c; MagickBooleanType status; PixelInfo pixel; Quantum *q; ssize_t x; size_t depth, one; ssize_t i, j, k, y; /* Initialize steganographic image attributes. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(watermark != (const Image *) NULL); assert(watermark->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); one=1UL; stegano_image=CloneImage(image,0,0,MagickTrue,exception); if (stegano_image == (Image *) NULL) return((Image *) NULL); stegano_image->depth=MAGICKCORE_QUANTUM_DEPTH; if (SetImageStorageClass(stegano_image,DirectClass,exception) == MagickFalse) { stegano_image=DestroyImage(stegano_image); return((Image *) NULL); } /* Hide watermark in low-order bits of image. */ c=0; i=0; j=0; depth=stegano_image->depth; k=stegano_image->offset; status=MagickTrue; watermark_view=AcquireVirtualCacheView(watermark,exception); stegano_view=AcquireAuthenticCacheView(stegano_image,exception); for (i=(ssize_t) depth-1; (i >= 0) && (j < (ssize_t) depth); i--) { for (y=0; (y < (ssize_t) watermark->rows) && (j < (ssize_t) depth); y++) { for (x=0; (x < (ssize_t) watermark->columns) && (j < (ssize_t) depth); x++) { ssize_t offset; (void) GetOneCacheViewVirtualPixelInfo(watermark_view,x,y,&pixel, exception); offset=k/(ssize_t) stegano_image->columns; if (offset >= (ssize_t) stegano_image->rows) break; q=GetCacheViewAuthenticPixels(stegano_view,k % (ssize_t) stegano_image->columns,k/(ssize_t) stegano_image->columns,1,1, exception); if (q == (Quantum *) NULL) break; switch (c) { case 0: { SetPixelRed(stegano_image,SetBit(GetPixelRed(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 1: { SetPixelGreen(stegano_image,SetBit(GetPixelGreen(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } case 2: { SetPixelBlue(stegano_image,SetBit(GetPixelBlue(stegano_image,q),j, GetBit(GetPixelInfoIntensity(stegano_image,&pixel),i)),q); break; } } if (SyncCacheViewAuthenticPixels(stegano_view,exception) == MagickFalse) break; c++; if (c == 3) c=0; k++; if (k == (ssize_t) (stegano_image->columns*stegano_image->columns)) k=0; if (k == stegano_image->offset) j++; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,SteganoImageTag,(MagickOffsetType) (depth-i),depth); if (proceed == MagickFalse) status=MagickFalse; } } stegano_view=DestroyCacheView(stegano_view); watermark_view=DestroyCacheView(watermark_view); if (status == MagickFalse) stegano_image=DestroyImage(stegano_image); return(stegano_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t e r e o A n a g l y p h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StereoAnaglyphImage() combines two images and produces a single image that % is the composite of a left and right image of a stereo pair. Special % red-green stereo glasses are required to view this effect. % % The format of the StereoAnaglyphImage method is: % % Image *StereoImage(const Image *left_image,const Image *right_image, % ExceptionInfo *exception) % Image *StereoAnaglyphImage(const Image *left_image, % const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o left_image: the left image. % % o right_image: the right image. % % o exception: return any errors or warnings in this structure. % % o x_offset: amount, in pixels, by which the left image is offset to the % right of the right image. % % o y_offset: amount, in pixels, by which the left image is offset to the % bottom of the right image. % % */ MagickExport Image *StereoImage(const Image *left_image, const Image *right_image,ExceptionInfo *exception) { return(StereoAnaglyphImage(left_image,right_image,0,0,exception)); } MagickExport Image *StereoAnaglyphImage(const Image *left_image, const Image *right_image,const ssize_t x_offset,const ssize_t y_offset, ExceptionInfo *exception) { #define StereoImageTag "Stereo/Image" const Image *image; Image *stereo_image; MagickBooleanType status; ssize_t y; assert(left_image != (const Image *) NULL); assert(left_image->signature == MagickCoreSignature); if (left_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", left_image->filename); assert(right_image != (const Image *) NULL); assert(right_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=left_image; if ((left_image->columns != right_image->columns) || (left_image->rows != right_image->rows)) ThrowImageException(ImageError,"LeftAndRightImageSizesDiffer"); /* Initialize stereo image attributes. */ stereo_image=CloneImage(left_image,left_image->columns,left_image->rows, MagickTrue,exception); if (stereo_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(stereo_image,DirectClass,exception) == MagickFalse) { stereo_image=DestroyImage(stereo_image); return((Image *) NULL); } (void) SetImageColorspace(stereo_image,sRGBColorspace,exception); /* Copy left image to red channel and right image to blue channel. */ status=MagickTrue; for (y=0; y < (ssize_t) stereo_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; ssize_t x; Quantum *magick_restrict r; p=GetVirtualPixels(left_image,-x_offset,y-y_offset,image->columns,1, exception); q=GetVirtualPixels(right_image,0,y,right_image->columns,1,exception); r=QueueAuthenticPixels(stereo_image,0,y,stereo_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL) || (r == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) stereo_image->columns; x++) { SetPixelRed(stereo_image,GetPixelRed(left_image,p),r); SetPixelGreen(stereo_image,GetPixelGreen(right_image,q),r); SetPixelBlue(stereo_image,GetPixelBlue(right_image,q),r); if ((GetPixelAlphaTraits(stereo_image) & CopyPixelTrait) != 0) SetPixelAlpha(stereo_image,(GetPixelAlpha(left_image,p)+ GetPixelAlpha(right_image,q))/2,r); p+=GetPixelChannels(left_image); q+=GetPixelChannels(right_image); r+=GetPixelChannels(stereo_image); } if (SyncAuthenticPixels(stereo_image,exception) == MagickFalse) break; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,StereoImageTag,(MagickOffsetType) y, stereo_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (status == MagickFalse) stereo_image=DestroyImage(stereo_image); return(stereo_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S w i r l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SwirlImage() swirls the pixels about the center of the image, where % degrees indicates the sweep of the arc through which each pixel is moved. % You get a more dramatic effect as the degrees move from 1 to 360. % % The format of the SwirlImage method is: % % Image *SwirlImage(const Image *image,double degrees, % const PixelInterpolateMethod method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o degrees: Define the tightness of the swirling effect. % % o method: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SwirlImage(const Image *image,double degrees, const PixelInterpolateMethod method,ExceptionInfo *exception) { #define SwirlImageTag "Swirl/Image" CacheView *canvas_view, *interpolate_view, *swirl_view; double radius; Image *canvas_image, *swirl_image; MagickBooleanType status; MagickOffsetType progress; PointInfo center, scale; ssize_t y; /* Initialize swirl 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); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); swirl_image=CloneImage(canvas_image,0,0,MagickTrue,exception); if (swirl_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(swirl_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); swirl_image=DestroyImage(swirl_image); return((Image *) NULL); } if (swirl_image->background_color.alpha_trait != UndefinedPixelTrait) (void) SetImageAlphaChannel(swirl_image,OnAlphaChannel,exception); /* Compute scaling factor. */ center.x=(double) canvas_image->columns/2.0; center.y=(double) canvas_image->rows/2.0; radius=MagickMax(center.x,center.y); scale.x=1.0; scale.y=1.0; if (canvas_image->columns > canvas_image->rows) scale.y=(double) canvas_image->columns/(double) canvas_image->rows; else if (canvas_image->columns < canvas_image->rows) scale.x=(double) canvas_image->rows/(double) canvas_image->columns; degrees=(double) DegreesToRadians(degrees); /* Swirl image. */ status=MagickTrue; progress=0; canvas_view=AcquireVirtualCacheView(canvas_image,exception); interpolate_view=AcquireVirtualCacheView(image,exception); swirl_view=AcquireAuthenticCacheView(swirl_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,swirl_image,canvas_image->rows,1) #endif for (y=0; y < (ssize_t) canvas_image->rows; y++) { double distance; PointInfo delta; const Quantum *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(swirl_view,0,y,swirl_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } delta.y=scale.y*(double) (y-center.y); for (x=0; x < (ssize_t) canvas_image->columns; x++) { /* Determine if the pixel is within an ellipse. */ delta.x=scale.x*(double) (x-center.x); distance=delta.x*delta.x+delta.y*delta.y; if (distance >= (radius*radius)) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(canvas_image); i++) { PixelChannel channel = GetPixelChannelChannel(canvas_image,i); PixelTrait traits = GetPixelChannelTraits(canvas_image,channel); PixelTrait swirl_traits = GetPixelChannelTraits(swirl_image, channel); if ((traits == UndefinedPixelTrait) || (swirl_traits == UndefinedPixelTrait)) continue; SetPixelChannel(swirl_image,channel,p[i],q); } } else { double cosine, factor, sine; /* Swirl the pixel. */ factor=1.0-sqrt((double) distance)/radius; sine=sin((double) (degrees*factor*factor)); cosine=cos((double) (degrees*factor*factor)); status=InterpolatePixelChannels(canvas_image,interpolate_view, swirl_image,method,((cosine*delta.x-sine*delta.y)/scale.x+center.x), (double) ((sine*delta.x+cosine*delta.y)/scale.y+center.y),q, exception); if (status == MagickFalse) break; } p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(swirl_image); } if (SyncCacheViewAuthenticPixels(swirl_view,exception) == MagickFalse) status=MagickFalse; if (canvas_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(canvas_image,SwirlImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } swirl_view=DestroyCacheView(swirl_view); interpolate_view=DestroyCacheView(interpolate_view); canvas_view=DestroyCacheView(canvas_view); canvas_image=DestroyImage(canvas_image); if (status == MagickFalse) swirl_image=DestroyImage(swirl_image); return(swirl_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T i n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TintImage() applies a color vector to each pixel in the image. The length % of the vector is 0 for black and white and at its maximum for the midtones. % The vector weighting function is f(x)=(1-(4.0*((x-0.5)*(x-0.5)))) % % The format of the TintImage method is: % % Image *TintImage(const Image *image,const char *blend, % const PixelInfo *tint,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o blend: A color value used for tinting. % % o tint: A color value used for tinting. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *TintImage(const Image *image,const char *blend, const PixelInfo *tint,ExceptionInfo *exception) { #define TintImageTag "Tint/Image" CacheView *image_view, *tint_view; double intensity; GeometryInfo geometry_info; Image *tint_image; MagickBooleanType status; MagickOffsetType progress; PixelInfo color_vector; MagickStatusType flags; ssize_t y; /* Allocate tint 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); tint_image=CloneImage(image,0,0,MagickTrue,exception); if (tint_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(tint_image,DirectClass,exception) == MagickFalse) { tint_image=DestroyImage(tint_image); return((Image *) NULL); } if ((IsGrayColorspace(image->colorspace) != MagickFalse) && (IsPixelInfoGray(tint) == MagickFalse)) (void) SetImageColorspace(tint_image,sRGBColorspace,exception); if (blend == (const char *) NULL) return(tint_image); /* Determine RGB values of the color. */ GetPixelInfo(image,&color_vector); flags=ParseGeometry(blend,&geometry_info); color_vector.red=geometry_info.rho; color_vector.green=geometry_info.rho; color_vector.blue=geometry_info.rho; color_vector.alpha=(MagickRealType) OpaqueAlpha; if ((flags & SigmaValue) != 0) color_vector.green=geometry_info.sigma; if ((flags & XiValue) != 0) color_vector.blue=geometry_info.xi; if ((flags & PsiValue) != 0) color_vector.alpha=geometry_info.psi; if (image->colorspace == CMYKColorspace) { color_vector.black=geometry_info.rho; if ((flags & PsiValue) != 0) color_vector.black=geometry_info.psi; if ((flags & ChiValue) != 0) color_vector.alpha=geometry_info.chi; } intensity=(double) GetPixelInfoIntensity((const Image *) NULL,tint); color_vector.red=(double) (color_vector.red*tint->red/100.0-intensity); color_vector.green=(double) (color_vector.green*tint->green/100.0-intensity); color_vector.blue=(double) (color_vector.blue*tint->blue/100.0-intensity); color_vector.black=(double) (color_vector.black*tint->black/100.0-intensity); color_vector.alpha=(double) (color_vector.alpha*tint->alpha/100.0-intensity); /* Tint image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); tint_view=AcquireAuthenticCacheView(tint_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,tint_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(tint_view,0,y,tint_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; double weight; GetPixelInfo(image,&pixel); weight=QuantumScale*GetPixelRed(image,p)-0.5; pixel.red=(MagickRealType) GetPixelRed(image,p)+color_vector.red* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelGreen(image,p)-0.5; pixel.green=(MagickRealType) GetPixelGreen(image,p)+color_vector.green* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlue(image,p)-0.5; pixel.blue=(MagickRealType) GetPixelBlue(image,p)+color_vector.blue* (1.0-(4.0*(weight*weight))); weight=QuantumScale*GetPixelBlack(image,p)-0.5; pixel.black=(MagickRealType) GetPixelBlack(image,p)+color_vector.black* (1.0-(4.0*(weight*weight))); pixel.alpha=(MagickRealType) GetPixelAlpha(image,p); SetPixelViaPixelInfo(tint_image,&pixel,q); p+=GetPixelChannels(image); q+=GetPixelChannels(tint_image); } if (SyncCacheViewAuthenticPixels(tint_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,TintImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } tint_view=DestroyCacheView(tint_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) tint_image=DestroyImage(tint_image); return(tint_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % V i g n e t t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % VignetteImage() softens the edges of the image in vignette style. % % The format of the VignetteImage method is: % % Image *VignetteImage(const Image *image,const double radius, % const double sigma,const ssize_t x,const ssize_t y, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o radius: the radius of the pixel neighborhood. % % o sigma: the standard deviation of the Gaussian, in pixels. % % o x, y: Define the x and y ellipse offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *VignetteImage(const Image *image,const double radius, const double sigma,const ssize_t x,const ssize_t y,ExceptionInfo *exception) { char ellipse[MagickPathExtent]; DrawInfo *draw_info; Image *canvas, *blur_image, *oval_image, *vignette_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); canvas=CloneImage(image,0,0,MagickTrue,exception); if (canvas == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(canvas,DirectClass,exception) == MagickFalse) { canvas=DestroyImage(canvas); return((Image *) NULL); } canvas->alpha_trait=BlendPixelTrait; oval_image=CloneImage(canvas,canvas->columns,canvas->rows,MagickTrue, exception); if (oval_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } (void) QueryColorCompliance("#000000",AllCompliance, &oval_image->background_color,exception); (void) SetImageBackgroundColor(oval_image,exception); draw_info=CloneDrawInfo((const ImageInfo *) NULL,(const DrawInfo *) NULL); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->fill, exception); (void) QueryColorCompliance("#ffffff",AllCompliance,&draw_info->stroke, exception); (void) FormatLocaleString(ellipse,MagickPathExtent,"ellipse %g,%g,%g,%g," "0.0,360.0",image->columns/2.0,image->rows/2.0,image->columns/2.0-x, image->rows/2.0-y); draw_info->primitive=AcquireString(ellipse); (void) DrawImage(oval_image,draw_info,exception); draw_info=DestroyDrawInfo(draw_info); blur_image=BlurImage(oval_image,radius,sigma,exception); oval_image=DestroyImage(oval_image); if (blur_image == (Image *) NULL) { canvas=DestroyImage(canvas); return((Image *) NULL); } blur_image->alpha_trait=UndefinedPixelTrait; (void) CompositeImage(canvas,blur_image,IntensityCompositeOp,MagickTrue, 0,0,exception); blur_image=DestroyImage(blur_image); vignette_image=MergeImageLayers(canvas,FlattenLayer,exception); canvas=DestroyImage(canvas); if (vignette_image != (Image *) NULL) (void) TransformImageColorspace(vignette_image,image->colorspace,exception); return(vignette_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveImage() creates a "ripple" effect in the image by shifting the pixels % vertically along a sine wave whose amplitude and wavelength is specified % by the given parameters. % % The format of the WaveImage method is: % % Image *WaveImage(const Image *image,const double amplitude, % const double wave_length,const PixelInterpolateMethod method, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o amplitude, wave_length: Define the amplitude and wave length of the % sine wave. % % o interpolate: the pixel interpolation method. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *WaveImage(const Image *image,const double amplitude, const double wave_length,const PixelInterpolateMethod method, ExceptionInfo *exception) { #define WaveImageTag "Wave/Image" CacheView *canvas_image_view, *wave_view; float *sine_map; Image *canvas_image, *wave_image; MagickBooleanType status; MagickOffsetType progress; ssize_t i; ssize_t y; /* Initialize wave image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) return((Image *) NULL); if ((canvas_image->alpha_trait == UndefinedPixelTrait) && (canvas_image->background_color.alpha != OpaqueAlpha)) (void) SetImageAlpha(canvas_image,OpaqueAlpha,exception); wave_image=CloneImage(canvas_image,canvas_image->columns,(size_t) (canvas_image->rows+2.0*fabs(amplitude)),MagickTrue,exception); if (wave_image == (Image *) NULL) { canvas_image=DestroyImage(canvas_image); return((Image *) NULL); } if (SetImageStorageClass(wave_image,DirectClass,exception) == MagickFalse) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); return((Image *) NULL); } /* Allocate sine map. */ sine_map=(float *) AcquireQuantumMemory((size_t) wave_image->columns, sizeof(*sine_map)); if (sine_map == (float *) NULL) { canvas_image=DestroyImage(canvas_image); wave_image=DestroyImage(wave_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } for (i=0; i < (ssize_t) wave_image->columns; i++) sine_map[i]=(float) fabs(amplitude)+amplitude*sin((double) ((2.0*MagickPI*i)*PerceptibleReciprocal(wave_length))); /* Wave image. */ status=MagickTrue; progress=0; canvas_image_view=AcquireVirtualCacheView(canvas_image,exception); wave_view=AcquireAuthenticCacheView(wave_image,exception); (void) SetCacheViewVirtualPixelMethod(canvas_image_view, BackgroundVirtualPixelMethod); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(canvas_image,wave_image,wave_image->rows,1) #endif for (y=0; y < (ssize_t) wave_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(canvas_image_view,0,y,canvas_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(wave_view,0,y,wave_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) wave_image->columns; x++) { status=InterpolatePixelChannels(canvas_image,canvas_image_view, wave_image,method,(double) x,(double) (y-sine_map[x]),q,exception); if (status == MagickFalse) break; p+=GetPixelChannels(canvas_image); q+=GetPixelChannels(wave_image); } if (SyncCacheViewAuthenticPixels(wave_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(canvas_image,WaveImageTag,progress, canvas_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } wave_view=DestroyCacheView(wave_view); canvas_image_view=DestroyCacheView(canvas_image_view); canvas_image=DestroyImage(canvas_image); sine_map=(float *) RelinquishMagickMemory(sine_map); if (status == MagickFalse) wave_image=DestroyImage(wave_image); return(wave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W a v e l e t D e n o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WaveletDenoiseImage() removes noise from the image using a wavelet % transform. The wavelet transform is a fast hierarchical scheme for % processing an image using a set of consecutive lowpass and high_pass filters, % followed by a decimation. This results in a decomposition into different % scales which can be regarded as different “frequency bands”, determined by % the mother wavelet. Adapted from dcraw.c by David Coffin. % % The format of the WaveletDenoiseImage method is: % % Image *WaveletDenoiseImage(const Image *image,const double threshold, % const double softness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: set the threshold for smoothing. % % o softness: attenuate the smoothing threshold. % % o exception: return any errors or warnings in this structure. % */ static inline void HatTransform(const float *magick_restrict pixels, const size_t stride,const size_t extent,const size_t scale,float *kernel) { const float *magick_restrict p, *magick_restrict q, *magick_restrict r; ssize_t i; p=pixels; q=pixels+scale*stride; r=pixels+scale*stride; for (i=0; i < (ssize_t) scale; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q-=stride; r+=stride; } for ( ; i < (ssize_t) (extent-scale); i++) { kernel[i]=0.25f*(2.0f*(*p)+*(p-scale*stride)+*(p+scale*stride)); p+=stride; } q=p-scale*stride; r=pixels+stride*(extent-2); for ( ; i < (ssize_t) extent; i++) { kernel[i]=0.25f*(*p+(*p)+(*q)+(*r)); p+=stride; q+=stride; r-=stride; } } MagickExport Image *WaveletDenoiseImage(const Image *image, const double threshold,const double softness,ExceptionInfo *exception) { CacheView *image_view, *noise_view; float *kernel, *pixels; Image *noise_image; MagickBooleanType status; MagickSizeType number_pixels; MemoryInfo *pixels_info; ssize_t channel; static const float noise_levels[] = { 0.8002f, 0.2735f, 0.1202f, 0.0585f, 0.0291f, 0.0152f, 0.0080f, 0.0044f }; /* Initialize noise 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 defined(MAGICKCORE_OPENCL_SUPPORT) noise_image=AccelerateWaveletDenoiseImage(image,threshold,exception); if (noise_image != (Image *) NULL) return(noise_image); #endif noise_image=CloneImage(image,0,0,MagickTrue,exception); if (noise_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(noise_image,DirectClass,exception) == MagickFalse) { noise_image=DestroyImage(noise_image); return((Image *) NULL); } if (AcquireMagickResource(WidthResource,4*image->columns) == MagickFalse) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); pixels_info=AcquireVirtualMemory(3*image->columns,image->rows* sizeof(*pixels)); kernel=(float *) AcquireQuantumMemory(MagickMax(image->rows,image->columns)+1, GetOpenMPMaximumThreads()*sizeof(*kernel)); if ((pixels_info == (MemoryInfo *) NULL) || (kernel == (float *) NULL)) { if (kernel != (float *) NULL) kernel=(float *) RelinquishMagickMemory(kernel); if (pixels_info != (MemoryInfo *) NULL) pixels_info=RelinquishVirtualMemory(pixels_info); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } pixels=(float *) GetVirtualMemoryBlob(pixels_info); status=MagickTrue; number_pixels=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); noise_view=AcquireAuthenticCacheView(noise_image,exception); for (channel=0; channel < (ssize_t) GetPixelChannels(image); channel++) { ssize_t i; size_t high_pass, low_pass; ssize_t level, y; PixelChannel pixel_channel; PixelTrait traits; if (status == MagickFalse) continue; traits=GetPixelChannelTraits(image,(PixelChannel) channel); if (traits == UndefinedPixelTrait) continue; pixel_channel=GetPixelChannelChannel(image,channel); if ((pixel_channel != RedPixelChannel) && (pixel_channel != GreenPixelChannel) && (pixel_channel != BluePixelChannel)) continue; /* Copy channel from image to wavelet pixel array. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (x=0; x < (ssize_t) image->columns; x++) { pixels[i++]=(float) p[channel]; p+=GetPixelChannels(image); } } /* Low pass filter outputs are called approximation kernel & high pass filters are referred to as detail kernel. The detail kernel have high values in the noisy parts of the signal. */ high_pass=0; for (level=0; level < 5; level++) { double magnitude; ssize_t x, y; low_pass=(size_t) (number_pixels*((level & 0x01)+1)); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); float *magick_restrict p, *magick_restrict q; ssize_t x; p=kernel+id*image->columns; q=pixels+y*image->columns; HatTransform(q+high_pass,1,image->columns,(size_t) (1UL << level),p); q+=low_pass; for (x=0; x < (ssize_t) image->columns; x++) *q++=(*p++); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,1) \ magick_number_threads(image,image,image->columns,1) #endif for (x=0; x < (ssize_t) image->columns; x++) { const int id = GetOpenMPThreadId(); float *magick_restrict p, *magick_restrict q; ssize_t y; p=kernel+id*image->rows; q=pixels+x+low_pass; HatTransform(q,image->columns,image->rows,(size_t) (1UL << level),p); for (y=0; y < (ssize_t) image->rows; y++) { *q=(*p++); q+=image->columns; } } /* To threshold, each coefficient is compared to a threshold value and attenuated / shrunk by some factor. */ magnitude=threshold*noise_levels[level]; for (i=0; i < (ssize_t) number_pixels; ++i) { pixels[high_pass+i]-=pixels[low_pass+i]; if (pixels[high_pass+i] < -magnitude) pixels[high_pass+i]+=magnitude-softness*magnitude; else if (pixels[high_pass+i] > magnitude) pixels[high_pass+i]-=magnitude-softness*magnitude; else pixels[high_pass+i]*=softness; if (high_pass != 0) pixels[i]+=pixels[high_pass+i]; } high_pass=low_pass; } /* Reconstruct image from the thresholded wavelet kernel. */ i=0; for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; Quantum *magick_restrict q; ssize_t x; ssize_t offset; q=GetCacheViewAuthenticPixels(noise_view,0,y,noise_image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; break; } offset=GetPixelChannelOffset(noise_image,pixel_channel); for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType pixel; pixel=(MagickRealType) pixels[i]+pixels[low_pass+i]; q[offset]=ClampToQuantum(pixel); i++; q+=GetPixelChannels(noise_image); } sync=SyncCacheViewAuthenticPixels(noise_view,exception); if (sync == MagickFalse) status=MagickFalse; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AddNoiseImageTag,(MagickOffsetType) channel,GetPixelChannels(image)); if (proceed == MagickFalse) status=MagickFalse; } } noise_view=DestroyCacheView(noise_view); image_view=DestroyCacheView(image_view); kernel=(float *) RelinquishMagickMemory(kernel); pixels_info=RelinquishVirtualMemory(pixels_info); if (status == MagickFalse) noise_image=DestroyImage(noise_image); return(noise_image); }
ljForce.c
/// \file /// Computes forces for the 12-6 Lennard Jones (LJ) potential. /// /// The Lennard-Jones model is not a good representation for the /// bonding in copper, its use has been limited to constant volume /// simulations where the embedding energy contribution to the cohesive /// energy is not included in the two-body potential /// /// The parameters here are taken from Wolf and Phillpot and fit to the /// room temperature lattice constant and the bulk melt temperature /// Ref: D. Wolf and S.Yip eds. Materials Interfaces (Chapman & Hall /// 1992) Page 230. /// /// Notes on LJ: /// /// http://en.wikipedia.org/wiki/Lennard_Jones_potential /// /// The total inter-atomic potential energy in the LJ model is: /// /// \f[ /// E_{tot} = \sum_{ij} U_{LJ}(r_{ij}) /// \f] /// \f[ /// U_{LJ}(r_{ij}) = 4 \epsilon /// \left\{ \left(\frac{\sigma}{r_{ij}}\right)^{12} /// - \left(\frac{\sigma}{r_{ij}}\right)^6 \right\} /// \f] /// /// where \f$\epsilon\f$ and \f$\sigma\f$ are the material parameters in the potential. /// - \f$\epsilon\f$ = well depth /// - \f$\sigma\f$ = hard sphere diameter /// /// To limit the interation range, the LJ potential is typically /// truncated to zero at some cutoff distance. A common choice for the /// cutoff distance is 2.5 * \f$\sigma\f$. /// This implementation can optionally shift the potential slightly /// upward so the value of the potential is zero at the cuotff /// distance. This shift has no effect on the particle dynamics. /// /// /// The force on atom i is given by /// /// \f[ /// F_i = -\nabla_i \sum_{jk} U_{LJ}(r_{jk}) /// \f] /// /// where the subsrcipt i on the gradient operator indicates that the /// derivatives are taken with respect to the coordinates of atom i. /// Liberal use of the chain rule leads to the expression /// /// \f{eqnarray*}{ /// F_i &=& - \sum_j U'_{LJ}(r_{ij})\hat{r}_{ij}\\ /// &=& \sum_j 24 \frac{\epsilon}{r_{ij}} \left\{ 2 \left(\frac{\sigma}{r_{ij}}\right)^{12} /// - \left(\frac{\sigma}{r_{ij}}\right)^6 \right\} \hat{r}_{ij} /// \f} /// /// where \f$\hat{r}_{ij}\f$ is a unit vector in the direction from atom /// i to atom j. /// /// #include "ljForce.h" #include <stdlib.h> #include <assert.h> #include <string.h> #include <omp.h> #include "constants.h" #include "mytype.h" #include "parallel.h" #include "linkCells.h" #include "memUtils.h" #include "CoMDTypes.h" #define POT_SHIFT 1.0 /// Derived struct for a Lennard Jones potential. /// Polymorphic with BasePotential. /// \see BasePotential typedef struct LjPotentialSt { real_t cutoff; //!< potential cutoff distance in Angstroms real_t mass; //!< mass of atoms in intenal units real_t lat; //!< lattice spacing (angs) of unit cell char latticeType[8]; //!< lattice type, e.g. FCC, BCC, etc. char name[3]; //!< element name int atomicNo; //!< atomic number int (*force)(SimFlat* s); //!< function pointer to force routine void (*print)(FILE* file, BasePotential* pot); void (*destroy)(BasePotential** pot); //!< destruction of the potential real_t sigma; real_t epsilon; } LjPotential; static int ljForce(SimFlat* s); static void ljPrint(FILE* file, BasePotential* pot); void ljDestroy(BasePotential** inppot) { if ( ! inppot ) return; LjPotential* pot = (LjPotential*)(*inppot); if ( ! pot ) return; comdFree(pot); *inppot = NULL; return; } /// Initialize an Lennard Jones potential for Copper. BasePotential* initLjPot(void) { LjPotential *pot = (LjPotential*)comdMalloc(sizeof(LjPotential)); pot->force = ljForce; pot->print = ljPrint; pot->destroy = ljDestroy; pot->sigma = 2.315; // Angstrom pot->epsilon = 0.167; // eV pot->mass = 63.55 * amuToInternalMass; // Atomic Mass Units (amu) pot->lat = 3.615; // Equilibrium lattice const in Angs strcpy(pot->latticeType, "FCC"); // lattice type, i.e. FCC, BCC, etc. pot->cutoff = 2.5*pot->sigma; // Potential cutoff in Angs strcpy(pot->name, "Cu"); pot->atomicNo = 29; return (BasePotential*) pot; } void ljPrint(FILE* file, BasePotential* pot) { LjPotential* ljPot = (LjPotential*) pot; fprintf(file, " Potential type : Lennard-Jones\n"); fprintf(file, " Species name : %s\n", ljPot->name); fprintf(file, " Atomic number : %d\n", ljPot->atomicNo); fprintf(file, " Mass : "FMT1" amu\n", ljPot->mass / amuToInternalMass); // print in amu fprintf(file, " Lattice Type : %s\n", ljPot->latticeType); fprintf(file, " Lattice spacing : "FMT1" Angstroms\n", ljPot->lat); fprintf(file, " Cutoff : "FMT1" Angstroms\n", ljPot->cutoff); fprintf(file, " Epsilon : "FMT1" eV\n", ljPot->epsilon); fprintf(file, " Sigma : "FMT1" Angstroms\n", ljPot->sigma); } int ljForce(SimFlat* s) { LjPotential* pot = (LjPotential *) s->pot; real_t sigma = pot->sigma; real_t epsilon = pot->epsilon; real_t rCut = pot->cutoff; real_t rCut2 = rCut*rCut; // zero forces and energy real_t ePot = 0.0; s->ePotential = 0.0; int fSize = s->boxes->nTotalBoxes*MAXATOMS; #pragma omp parallel for for (int ii=0; ii<fSize; ++ii) { zeroReal3(s->atoms->f[ii]); s->atoms->U[ii] = 0.; } real_t s6 = sigma*sigma*sigma*sigma*sigma*sigma; real_t rCut6 = s6 / (rCut2*rCut2*rCut2); real_t eShift = POT_SHIFT * rCut6 * (rCut6 - 1.0); int nNbrBoxes = 27; // loop over local boxes #pragma omp parallel for reduction(+:ePot) for (int iBox=0; iBox<s->boxes->nLocalBoxes; iBox++) { int nIBox = s->boxes->nAtoms[iBox]; // loop over neighbors of iBox for (int jTmp=0; jTmp<nNbrBoxes; jTmp++) { int jBox = s->boxes->nbrBoxes[iBox][jTmp]; assert(jBox>=0); int nJBox = s->boxes->nAtoms[jBox]; // loop over atoms in iBox for (int iOff=MAXATOMS*iBox; iOff<(iBox*MAXATOMS+nIBox); iOff++) { // loop over atoms in jBox for (int jOff=jBox*MAXATOMS; jOff<(jBox*MAXATOMS+nJBox); jOff++) { real3 dr; real_t r2 = 0.0; for (int m=0; m<3; m++) { dr[m] = s->atoms->r[iOff][m]-s->atoms->r[jOff][m]; r2+=dr[m]*dr[m]; } if ( r2 <= rCut2 && r2 > 0.0) { // Important note: // from this point on r actually refers to 1.0/r r2 = 1.0/r2; real_t r6 = s6 * (r2*r2*r2); real_t eLocal = r6 * (r6 - 1.0) - eShift; s->atoms->U[iOff] += 0.5*eLocal; ePot += 0.5*eLocal; // different formulation to avoid sqrt computation real_t fr = - 4.0*epsilon*r6*r2*(12.0*r6 - 6.0); for (int m=0; m<3; m++) { s->atoms->f[iOff][m] -= dr[m]*fr; } } } // loop over atoms in jBox } // loop over atoms in iBox } // loop over neighbor boxes } // loop over local boxes in system ePot = ePot*4.0*epsilon; s->ePotential = ePot; return 0; }
GB_binop__min_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_int64) // A.*B function (eWiseMult): GB (_AemultB_08__min_int64) // A.*B function (eWiseMult): GB (_AemultB_02__min_int64) // A.*B function (eWiseMult): GB (_AemultB_04__min_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int64) // A*D function (colscale): GB (_AxD__min_int64) // D*A function (rowscale): GB (_DxB__min_int64) // C+=B function (dense accum): GB (_Cdense_accumB__min_int64) // C+=b function (dense accum): GB (_Cdense_accumb__min_int64) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int64) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int64) // C=scalar+B GB (_bind1st__min_int64) // C=scalar+B' GB (_bind1st_tran__min_int64) // C=A+scalar GB (_bind2nd__min_int64) // C=A'+scalar GB (_bind2nd_tran__min_int64) // C type: int64_t // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_t aij = GBX (Ax, pA, A_iso) // 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) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_INT64 || GxB_NO_MIN_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__min_int64) ( 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__min_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__min_int64) ( 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 int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__min_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__min_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__min_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
phylokernelsafe.h
/* * phylokernelsafe.h * Safe likelihood kernel that scales likelihood per category * * Created on: Sept 23, 2016 * Author: minh */ #ifndef PHYLOKERNELSAFE_H_ #define PHYLOKERNELSAFE_H_ #include "phylotree.h" //#include "vectorclass/vectorclass.h" //#include "vectorclass/vectormath_exp.h" #include "superalignment.h" #ifdef __SSE__ inline Vec2d horizontal_add(Vec2d x[2]) { #if INSTRSET >= 3 // SSE3 return _mm_hadd_pd(x[0],x[1]); #elif INSTRSET >= 2 Vec2d help0 = _mm_shuffle_pd(x[0], x[1], _MM_SHUFFLE2(0,0)); Vec2d help1 = _mm_shuffle_pd(x[0], x[1], _MM_SHUFFLE2(1,1)); return _mm_add_pd(help0, help1); #else #error "You must compile with SSE2 enabled!" #endif } inline double horizontal_max(Vec2d const &a) { double x[2]; a.store(x); return max(x[0],x[1]); } #endif #ifdef __AVX__ inline Vec4d horizontal_add(Vec4d x[4]) { // {a[0]+a[1], b[0]+b[1], a[2]+a[3], b[2]+b[3]} __m256d sumab = _mm256_hadd_pd(x[0], x[1]); // {c[0]+c[1], d[0]+d[1], c[2]+c[3], d[2]+d[3]} __m256d sumcd = _mm256_hadd_pd(x[2], x[3]); // {a[0]+a[1], b[0]+b[1], c[2]+c[3], d[2]+d[3]} __m256d blend = _mm256_blend_pd(sumab, sumcd, 12/* 0b1100*/); // {a[2]+a[3], b[2]+b[3], c[0]+c[1], d[0]+d[1]} __m256d perm = _mm256_permute2f128_pd(sumab, sumcd, 0x21); return _mm256_add_pd(perm, blend); } inline double horizontal_max(Vec4d const &a) { __m128d high = _mm256_extractf128_pd(a,1); __m128d m = _mm_max_pd(_mm256_castpd256_pd128(a), high); double x[2]; _mm_storeu_pd(x, m); return max(x[0],x[1]); } #endif // __AVX__ template <class Numeric, class VectorClass, const int VCSIZE> Numeric PhyloTree::dotProductSIMD(Numeric *x, Numeric *y, int size) { VectorClass res = VectorClass().load_a(x) * VectorClass().load_a(y); for (int i = VCSIZE; i < size; i += VCSIZE) res = mul_add(VectorClass().load_a(&x[i]), VectorClass().load_a(&y[i]), res); return horizontal_add(res); } /************************************************************************************************ * * Highly optimized vectorized versions of likelihood functions * *************************************************************************************************/ template <class VectorClass, const int VCSIZE, const int nstates> void PhyloTree::computePartialLikelihoodEigenSIMD(PhyloNeighbor *dad_branch, PhyloNode *dad) { // don't recompute the likelihood ASSERT(dad); if (dad_branch->partial_lh_computed & 1) return; dad_branch->partial_lh_computed |= 1; num_partial_lh_computations++; size_t nptn = aln->size() + model_factory->unobserved_ptns.size(); PhyloNode *node = (PhyloNode*)(dad_branch->node); if (!tip_partial_lh_computed) computeTipPartialLikelihood(); if (node->isLeaf()) { dad_branch->lh_scale_factor = 0.0; //memset(dad_branch->scale_num, 0, nptn * sizeof(UBYTE)); return; } size_t ptn, c; size_t orig_nptn = aln->size(); size_t ncat = site_rate->getNRate(); size_t ncat_mix = (model_factory->fused_mix_rate) ? ncat : ncat*model->getNMixtures(); ASSERT(nstates == aln->num_states && nstates >= VCSIZE && VCSIZE == VectorClass().size()); ASSERT(model->isReversible()); // only works with reversible model! const size_t nstatesqr=nstates*nstates; size_t i, x, j; size_t block = nstates * ncat_mix; size_t tip_block = nstates * model->getNMixtures(); size_t scale_size = nptn * ncat_mix; size_t mix_addr_nstates[ncat_mix], mix_addr[ncat_mix]; size_t denom = (model_factory->fused_mix_rate) ? 1 : ncat; for (c = 0; c < ncat_mix; c++) { size_t m = c/denom; mix_addr_nstates[c] = m*nstates; mix_addr[c] = m*nstatesqr; } // internal node dad_branch->lh_scale_factor = 0.0; PhyloNeighbor *left = NULL, *right = NULL; // left & right are two neighbors leading to 2 subtrees int num_leaves = 0; FOR_NEIGHBOR_IT(node, dad, it) { PhyloNeighbor *nei = (PhyloNeighbor*)*it; if (!left) left = (PhyloNeighbor*)(*it); else right = (PhyloNeighbor*)(*it); if ((nei->partial_lh_computed & 1) == 0) computePartialLikelihoodEigenSIMD<VectorClass, VCSIZE, nstates>(nei, node); dad_branch->lh_scale_factor += nei->lh_scale_factor; if ((*it)->node->isLeaf()) num_leaves++; } if (params->lh_mem_save == LM_PER_NODE && !dad_branch->partial_lh) { // re-orient partial_lh bool done = false; FOR_NEIGHBOR_IT(node, dad, it2) { PhyloNeighbor *backnei = ((PhyloNeighbor*)(*it2)->node->findNeighbor(node)); if (backnei->partial_lh) { dad_branch->partial_lh = backnei->partial_lh; dad_branch->scale_num = backnei->scale_num; backnei->partial_lh = NULL; backnei->scale_num = NULL; backnei->partial_lh_computed &= ~1; // clear bit done = true; break; } } ASSERT(done && "partial_lh is not re-oriented"); } double *evec = model->getEigenvectors(); double *inv_evec = model->getInverseEigenvectors(); ASSERT(inv_evec && evec); // for (i = 0; i < tip_block; i++) { // for (x = 0; x < nstates/VCSIZE; x++) // // inv_evec is not aligned! // vc_inv_evec[i*nstates/VCSIZE+x].load_a(&inv_evec[i*nstates+x*VCSIZE]); // } double *eval = model->getEigenvalues(); VectorClass *echildren = aligned_alloc<VectorClass>(block*nstates/VCSIZE*(node->degree()-1)); double *partial_lh_leaves = NULL; if (num_leaves > 0) partial_lh_leaves = aligned_alloc<double>((aln->STATE_UNKNOWN+1)*block*num_leaves); VectorClass *echild = echildren; double *partial_lh_leaf = partial_lh_leaves; FOR_NEIGHBOR_IT(node, dad, it) { VectorClass expchild[nstates/VCSIZE]; PhyloNeighbor *child = (PhyloNeighbor*)*it; VectorClass *echild_ptr = echild; // precompute information buffer for (c = 0; c < ncat_mix; c++) { VectorClass len_child = site_rate->getRate(c%ncat) * child->length; double *eval_ptr = eval + mix_addr_nstates[c]; double *evec_ptr = evec + mix_addr[c]; for (i = 0; i < nstates/VCSIZE; i++) { // eval is not aligned! expchild[i] = exp(VectorClass().load_a(&eval_ptr[i*VCSIZE]) * len_child); } for (x = 0; x < nstates; x++) { for (i = 0; i < nstates/VCSIZE; i++) { // evec is not be aligned! echild_ptr[i] = (VectorClass().load_a(&evec_ptr[x*nstates+i*VCSIZE]) * expchild[i]); } echild_ptr += nstates/VCSIZE; } } // pre compute information for tip if (child->node->isLeaf()) { vector<int>::iterator it; for (it = aln->seq_states[child->node->id].begin(); it != aln->seq_states[child->node->id].end(); it++) { int state = (*it); double *this_partial_lh_leaf = partial_lh_leaf + state*block; VectorClass *echild_ptr = echild; for (c = 0; c < ncat_mix; c++) { VectorClass *this_tip_partial_lh = (VectorClass*)(tip_partial_lh + state*tip_block + mix_addr_nstates[c]); for (x = 0; x < nstates; x++) { VectorClass vchild = 0.0; for (i = 0; i < nstates/VCSIZE; i++) { vchild += echild_ptr[i] * this_tip_partial_lh[i]; } this_partial_lh_leaf[x] = horizontal_add(vchild); echild_ptr += nstates/VCSIZE; } this_partial_lh_leaf += nstates; } } size_t addr = aln->STATE_UNKNOWN * block; for (x = 0; x < block; x++) { partial_lh_leaf[addr+x] = 1.0; } partial_lh_leaf += (aln->STATE_UNKNOWN+1)*block; } echild += block*nstates/VCSIZE; } VectorClass *eleft = echildren, *eright = echildren + block*nstates/VCSIZE; if (!left->node->isLeaf() && right->node->isLeaf()) { PhyloNeighbor *tmp = left; left = right; right = tmp; VectorClass *etmp = eleft; eleft = eright; eright = etmp; } if (node->degree() > 3) { /*--------------------- multifurcating node ------------------*/ // now for-loop computing partial_lh over all site-patterns #ifdef _OPENMP #pragma omp parallel for private(ptn, c, x, i) schedule(static) #endif for (ptn = 0; ptn < nptn; ptn++) { double partial_lh_all[block]; for (i = 0; i < block; i++) partial_lh_all[i] = 1.0; UBYTE *scale_dad = dad_branch->scale_num + ptn*ncat_mix; memset(scale_dad, 0, sizeof(UBYTE)*ncat_mix); double *partial_lh_leaf = partial_lh_leaves; double *echild = (double*)echildren; FOR_NEIGHBOR_IT(node, dad, it) { PhyloNeighbor *child = (PhyloNeighbor*)*it; UBYTE *scale_child = child->scale_num + ptn*ncat_mix; if (child->node->isLeaf()) { // external node int state_child = (ptn < orig_nptn) ? (aln->at(ptn))[child->node->id] : model_factory->unobserved_ptns[ptn-orig_nptn]; double *child_lh = partial_lh_leaf + state_child*block; for (c = 0; c < block; c++) { // compute real partial likelihood vector partial_lh_all[c] *= child_lh[c]; } partial_lh_leaf += (aln->STATE_UNKNOWN+1)*block; } else { // internal node double *partial_lh = partial_lh_all; double *partial_lh_child = child->partial_lh + ptn*block; double *echild_ptr = echild; for (c = 0; c < ncat_mix; c++) { scale_dad[c] += scale_child[c]; // compute real partial likelihood vector for (x = 0; x < nstates; x++) { double vchild = 0.0; // double *echild_ptr = echild + (c*nstatesqr+x*nstates); for (i = 0; i < nstates; i++) { vchild += echild_ptr[i] * partial_lh_child[i]; } echild_ptr += nstates; partial_lh[x] *= vchild; } partial_lh += nstates; partial_lh_child += nstates; } } // if echild += block*nstates; } // FOR_NEIGHBOR // compute dot-product with inv_eigenvector double *partial_lh_tmp = partial_lh_all; double *partial_lh = dad_branch->partial_lh + ptn*block; for (c = 0; c < ncat_mix; c++) { double lh_max = 0.0; double *inv_evec_ptr = inv_evec + mix_addr[c]; for (i = 0; i < nstates; i++) { double res = 0.0; for (x = 0; x < nstates; x++) { res += partial_lh_tmp[x]*inv_evec_ptr[x]; } inv_evec_ptr += nstates; partial_lh[i] = res; lh_max = max(lh_max, fabs(res)); } // check if one should scale partial likelihoods if (lh_max < SCALING_THRESHOLD && lh_max != 0.0) { if (ptn_invar[ptn] == 0.0) { // now do the likelihood scaling for (i = 0; i < nstates; i++) partial_lh[i] *= SCALING_THRESHOLD_INVER; scale_dad[c] += 1; } } partial_lh += nstates; partial_lh_tmp += nstates; } } // for ptn // end multifurcating treatment } else if (left->node->isLeaf() && right->node->isLeaf()) { // special treatment for TIP-TIP (cherry) case // pre compute information for both tips double *partial_lh_left = partial_lh_leaves; double *partial_lh_right = partial_lh_leaves + (aln->STATE_UNKNOWN+1)*block; // assign pointers for left and right partial_lh /* double **lh_left_ptr = aligned_alloc<double*>(nptn); double **lh_right_ptr = aligned_alloc<double*>(nptn); for (ptn = 0; ptn < orig_ntn; ptn++) { lh_left_ptr[ptn] = &partial_lh_left[block * (aln->at(ptn))[left->node->id]]; lh_right_ptr[ptn] = &partial_lh_right[block * (aln->at(ptn))[right->node->id]]; } for (ptn = orig_ntn; ptn < nptn; ptn++) { lh_left_ptr[ptn] = &partial_lh_left[block * model_factory->unobserved_ptns[ptn-orig_ntn]]; lh_right_ptr[ptn] = &partial_lh_right[block * model_factory->unobserved_ptns[ptn-orig_ntn]]; } */ // scale number must be ZERO memset(dad_branch->scale_num, 0, scale_size * sizeof(UBYTE)); VectorClass vc_partial_lh_tmp[nstates/VCSIZE]; VectorClass res[VCSIZE]; #ifdef _OPENMP #pragma omp parallel for private(ptn, c, x, i, j, vc_partial_lh_tmp, res) #endif for (ptn = 0; ptn < nptn; ptn++) { double *partial_lh = dad_branch->partial_lh + ptn*block; double *lh_left; double *lh_right; if (ptn < orig_nptn) { lh_left = &partial_lh_left[block * (aln->at(ptn))[left->node->id]]; lh_right = &partial_lh_right[block * (aln->at(ptn))[right->node->id]]; } else { lh_left = &partial_lh_left[block * model_factory->unobserved_ptns[ptn-orig_nptn]]; lh_right = &partial_lh_right[block * model_factory->unobserved_ptns[ptn-orig_nptn]]; } for (c = 0; c < ncat_mix; c++) { VectorClass *vc_inv_evec_ptr = (VectorClass*)(inv_evec + mix_addr[c]); // compute real partial likelihood vector for (x = 0; x < nstates/VCSIZE; x++) { vc_partial_lh_tmp[x] = (VectorClass().load_a(&lh_left[x*VCSIZE]) * VectorClass().load_a(&lh_right[x*VCSIZE])); } // compute dot-product with inv_eigenvector for (i = 0; i < nstates; i+=VCSIZE) { for (j = 0; j < VCSIZE; j++) { res[j] = vc_partial_lh_tmp[0] * vc_inv_evec_ptr[(i+j)*nstates/VCSIZE]; } for (x = 1; x < nstates/VCSIZE; x++) for (j = 0; j < VCSIZE; j++) { res[j] = mul_add(vc_partial_lh_tmp[x], vc_inv_evec_ptr[(i+j)*nstates/VCSIZE+x], res[j]); } horizontal_add(res).store_a(&partial_lh[i]); } lh_left += nstates; lh_right += nstates; partial_lh += nstates; } } //aligned_free(lh_right_ptr); //aligned_free(lh_left_ptr); } else if (left->node->isLeaf() && !right->node->isLeaf()) { // special treatment to TIP-INTERNAL NODE case // only take scale_num from the right subtree memcpy(dad_branch->scale_num, right->scale_num, scale_size * sizeof(UBYTE)); // pre compute information for left tip double *partial_lh_left = partial_lh_leaves; // assign pointers for partial_lh_left /* double **lh_left_ptr = aligned_alloc<double*>(nptn); for (ptn = 0; ptn < orig_ntn; ptn++) { lh_left_ptr[ptn] = &partial_lh_left[block * (aln->at(ptn))[left->node->id]]; } for (ptn = orig_ntn; ptn < nptn; ptn++) { lh_left_ptr[ptn] = &partial_lh_left[block * model_factory->unobserved_ptns[ptn-orig_ntn]]; } */ VectorClass vc_lh_right[nstates/VCSIZE]; VectorClass vc_partial_lh_tmp[nstates/VCSIZE]; VectorClass res[VCSIZE]; VectorClass vc_max; // maximum of partial likelihood, for scaling check VectorClass vright[VCSIZE]; #ifdef _OPENMP #pragma omp parallel for private (ptn, c, x, i, j, vc_lh_right, vc_partial_lh_tmp, res, vc_max, vright) #endif for (ptn = 0; ptn < nptn; ptn++) { double *partial_lh = dad_branch->partial_lh + ptn*block; double *partial_lh_right = right->partial_lh + ptn*block; double *lh_left; if (ptn < orig_nptn) { lh_left = &partial_lh_left[block * (aln->at(ptn))[left->node->id]]; } else { lh_left = &partial_lh_left[block * model_factory->unobserved_ptns[ptn-orig_nptn]]; } for (c = 0; c < ncat_mix; c++) { vc_max = 0.0; VectorClass *vc_inv_evec_ptr = (VectorClass*)(inv_evec + mix_addr[c]); // compute real partial likelihood vector for (i = 0; i < nstates/VCSIZE; i++) vc_lh_right[i].load_a(&partial_lh_right[i*VCSIZE]); for (x = 0; x < nstates/VCSIZE; x++) { size_t addr = c*nstatesqr/VCSIZE+x*nstates; for (j = 0; j < VCSIZE; j++) { vright[j] = eright[addr+nstates*j/VCSIZE] * vc_lh_right[0]; } for (i = 1; i < nstates/VCSIZE; i++) for (j = 0; j < VCSIZE; j++) { vright[j] = mul_add(eright[addr+i+nstates*j/VCSIZE], vc_lh_right[i], vright[j]); } vc_partial_lh_tmp[x] = VectorClass().load_a(&lh_left[x*VCSIZE]) * horizontal_add(vright); } // compute dot-product with inv_eigenvector for (i = 0; i < nstates; i+=VCSIZE) { for (j = 0; j < VCSIZE; j++) { res[j] = vc_partial_lh_tmp[0] * vc_inv_evec_ptr[(i+j)*nstates/VCSIZE]; } for (x = 1; x < nstates/VCSIZE; x++) { for (j = 0; j < VCSIZE; j++) { res[j] = mul_add(vc_partial_lh_tmp[x], vc_inv_evec_ptr[(i+j)*nstates/VCSIZE+x], res[j]); } } VectorClass sum_res = horizontal_add(res); sum_res.store_a(&partial_lh[i]); vc_max = max(vc_max, abs(sum_res)); // take the maximum for scaling check } // check if one should scale partial likelihoods double lh_max = horizontal_max(vc_max); if (lh_max < SCALING_THRESHOLD && ptn_invar[ptn] == 0.0 && lh_max != 0.0) { // now do the likelihood scaling VectorClass scale_thres(SCALING_THRESHOLD_INVER); for (i = 0; i < block; i+=VCSIZE) { (VectorClass().load_a(&partial_lh[i]) * scale_thres).store_a(&partial_lh[i]); } dad_branch->scale_num[ptn*ncat_mix+c] += 1; } lh_left += nstates; partial_lh_right += nstates; partial_lh += nstates; } } } else { // both left and right are internal node VectorClass vc_max; // maximum of partial likelihood, for scaling check VectorClass vc_partial_lh_tmp[nstates/VCSIZE]; VectorClass vc_lh_left[nstates/VCSIZE], vc_lh_right[nstates/VCSIZE]; VectorClass res[VCSIZE]; VectorClass vleft[VCSIZE], vright[VCSIZE]; #ifdef _OPENMP #pragma omp parallel for private(ptn, c, x, i, j, vc_max, vc_partial_lh_tmp, vc_lh_left, vc_lh_right, res, vleft, vright) #endif for (ptn = 0; ptn < nptn; ptn++) { double *partial_lh = dad_branch->partial_lh + ptn*block; double *partial_lh_left = left->partial_lh + ptn*block; double *partial_lh_right = right->partial_lh + ptn*block; UBYTE *scale_dad = dad_branch->scale_num + ptn*ncat_mix; UBYTE *scale_left = left->scale_num + ptn*ncat_mix; UBYTE *scale_right = right->scale_num + ptn*ncat_mix; for (c = 0; c < ncat_mix; c++) { scale_dad[c] = scale_left[c] + scale_right[c]; vc_max = 0.0; VectorClass *vc_inv_evec_ptr = (VectorClass*)(inv_evec + mix_addr[c]); // compute real partial likelihood vector for (i = 0; i < nstates/VCSIZE; i++) { vc_lh_left[i].load_a(&partial_lh_left[i*VCSIZE]); vc_lh_right[i].load_a(&partial_lh_right[i*VCSIZE]); } for (x = 0; x < nstates/VCSIZE; x++) { size_t addr = c*nstatesqr/VCSIZE+x*nstates; for (j = 0; j < VCSIZE; j++) { size_t addr_com = addr+j*nstates/VCSIZE; vleft[j] = eleft[addr_com] * vc_lh_left[0]; vright[j] = eright[addr_com] * vc_lh_right[0]; } for (i = 1; i < nstates/VCSIZE; i++) { for (j = 0; j < VCSIZE; j++) { size_t addr_com = addr+i+j*nstates/VCSIZE; vleft[j] = mul_add(eleft[addr_com], vc_lh_left[i], vleft[j]); vright[j] = mul_add(eright[addr_com], vc_lh_right[i], vright[j]); } } vc_partial_lh_tmp[x] = horizontal_add(vleft) * horizontal_add(vright); } // compute dot-product with inv_eigenvector for (i = 0; i < nstates; i+=VCSIZE) { for (j = 0; j < VCSIZE; j++) { res[j] = vc_partial_lh_tmp[0] * vc_inv_evec_ptr[(i+j)*nstates/VCSIZE]; } for (x = 1; x < nstates/VCSIZE; x++) for (j = 0; j < VCSIZE; j++) res[j] = mul_add(vc_partial_lh_tmp[x], vc_inv_evec_ptr[(i+j)*nstates/VCSIZE+x], res[j]); VectorClass sum_res = horizontal_add(res); sum_res.store_a(&partial_lh[i]); vc_max = max(vc_max, abs(sum_res)); // take the maximum for scaling check } // check if one should scale partial likelihoods double lh_max = horizontal_max(vc_max); if (lh_max < SCALING_THRESHOLD && ptn_invar[ptn] == 0.0 && lh_max != 0.0) { // now do the likelihood scaling VectorClass scale_thres(SCALING_THRESHOLD_INVER); for (i = 0; i < block; i+=VCSIZE) { (VectorClass().load_a(&partial_lh[i]) * scale_thres).store_a(&partial_lh[i]); } // unobserved const pattern will never have underflow scale_dad[c] += 1; } partial_lh += nstates; partial_lh_left += nstates; partial_lh_right += nstates; } } } if (partial_lh_leaves) aligned_free(partial_lh_leaves); aligned_free(echildren); } template <class VectorClass, const int VCSIZE, const int nstates> void PhyloTree::computeLikelihoodDervEigenSIMD(PhyloNeighbor *dad_branch, PhyloNode *dad, double &df, double &ddf) { PhyloNode *node = (PhyloNode*) dad_branch->node; PhyloNeighbor *node_branch = (PhyloNeighbor*) node->findNeighbor(dad); if (!central_partial_lh) initializeAllPartialLh(); if (node->isLeaf()) { PhyloNode *tmp_node = dad; dad = node; node = tmp_node; PhyloNeighbor *tmp_nei = dad_branch; dad_branch = node_branch; node_branch = tmp_nei; } if ((dad_branch->partial_lh_computed & 1) == 0) computePartialLikelihoodEigenSIMD<VectorClass, VCSIZE, nstates>(dad_branch, dad); if ((node_branch->partial_lh_computed & 1) == 0) computePartialLikelihoodEigenSIMD<VectorClass, VCSIZE, nstates>(node_branch, node); df = ddf = 0.0; size_t ncat = site_rate->getNRate(); size_t ncat_mix = (model_factory->fused_mix_rate) ? ncat : ncat*model->getNMixtures(); size_t block = ncat_mix * nstates; size_t tip_block = nstates * model->getNMixtures(); size_t ptn; // for big data size > 4GB memory required size_t c, i, j; size_t orig_nptn = aln->size(); size_t nptn = aln->size()+model_factory->unobserved_ptns.size(); size_t maxptn = ((nptn+VCSIZE-1)/VCSIZE)*VCSIZE; maxptn = max(maxptn, aln->size()+((model_factory->unobserved_ptns.size()+VCSIZE-1)/VCSIZE)*VCSIZE); size_t mix_addr_nstates[ncat_mix]; size_t denom = (model_factory->fused_mix_rate) ? 1 : ncat; double *eval = model->getEigenvalues(); ASSERT(eval); VectorClass *vc_val0 = (VectorClass*)aligned_alloc<double>(block); VectorClass *vc_val1 = (VectorClass*)aligned_alloc<double>(block); VectorClass *vc_val2 = (VectorClass*)aligned_alloc<double>(block); VectorClass vc_len = dad_branch->length; for (c = 0; c < ncat_mix; c++) { size_t m = c/denom; mix_addr_nstates[c] = m*nstates; size_t mycat = c%ncat; double *eval_ptr = eval + m*nstates; VectorClass vc_rate = site_rate->getRate(mycat); VectorClass vc_prop = site_rate->getProp(mycat) * model->getMixtureWeight(m); for (i = 0; i < nstates/VCSIZE; i++) { VectorClass cof = VectorClass().load_a(&eval_ptr[i*VCSIZE]) * vc_rate; VectorClass val = exp(cof*vc_len) * vc_prop; VectorClass val1_ = cof*val; vc_val0[c*nstates/VCSIZE+i] = val; vc_val1[c*nstates/VCSIZE+i] = val1_; vc_val2[c*nstates/VCSIZE+i] = cof*val1_; } } ASSERT(theta_all); if (!theta_computed) { theta_computed = true; double scale_all = 0.0; // precompute theta for fast branch length optimization if (dad->isLeaf()) { // special treatment for TIP-INTERNAL NODE case #ifdef _OPENMP #pragma omp parallel for private(ptn, i, c) reduction(+: scale_all) #endif for (ptn = 0; ptn < nptn; ptn++) { double *partial_lh_dad = dad_branch->partial_lh + ptn*block; UBYTE *scale_dad = dad_branch->scale_num+ptn*ncat_mix; double *theta = theta_all + ptn*block; double *this_tip_partial_lh = tip_partial_lh + tip_block*((ptn < orig_nptn) ? (aln->at(ptn))[dad->id] : model_factory->unobserved_ptns[ptn-orig_nptn]); UBYTE min_scale = scale_dad[0]; for (c = 1; c < ncat_mix; c++) min_scale = min(min_scale, scale_dad[c]); scale_all += (double)min_scale; for (c = 0; c < ncat_mix; c++) { double *lh_dad = this_tip_partial_lh + mix_addr_nstates[c]; if (scale_dad[c] == min_scale) { for (i = 0; i < nstates; i+=VCSIZE) { (VectorClass().load_a(&lh_dad[i]) * VectorClass().load_a(&partial_lh_dad[i])).store_a(&theta[i]); } } else if (scale_dad[c] == min_scale+1) { for (i = 0; i < nstates; i+=VCSIZE) { (VectorClass().load_a(&lh_dad[i]) * VectorClass().load_a(&partial_lh_dad[i]) * VectorClass(SCALING_THRESHOLD)).store_a(&theta[i]); } } else { memset(theta, 0, sizeof(double)*nstates); } partial_lh_dad += nstates; theta += nstates; } } } else { // both dad and node are internal nodes #ifdef _OPENMP #pragma omp parallel for private(i, c) reduction(+: scale_all) #endif for (ptn = 0; ptn < nptn; ptn++) { double *theta = theta_all + ptn*block; double *partial_lh_node = node_branch->partial_lh + ptn*block; double *partial_lh_dad = dad_branch->partial_lh + ptn*block; size_t ptn_ncat = ptn*ncat_mix; UBYTE *scale_dad = dad_branch->scale_num + ptn_ncat; UBYTE *scale_node = node_branch->scale_num + ptn_ncat; UBYTE sum_scale[ncat_mix]; UBYTE min_scale = sum_scale[0] = scale_dad[0] + scale_node[0]; for (c = 1; c < ncat_mix; c++) { sum_scale[c] = scale_dad[c] + scale_node[c]; min_scale = min(min_scale, sum_scale[c]); } scale_all += (double)min_scale; for (c = 0; c < ncat_mix; c++) { if (sum_scale[c] == min_scale) { for (i = 0; i < nstates; i++) { (VectorClass().load_a(&partial_lh_node[i]) * VectorClass().load_a(&partial_lh_dad[i])).store_a(&theta[i]); } } else if (sum_scale[c] == min_scale+1) { for (i = 0; i < nstates; i++) { (VectorClass().load_a(&partial_lh_node[i]) * VectorClass().load_a(&partial_lh_dad[i]) * VectorClass(SCALING_THRESHOLD)).store_a(&theta[i]); } } else { memset(theta, 0, sizeof(double)*nstates); } theta += nstates; partial_lh_dad += nstates; partial_lh_node += nstates; } } } if (nptn < maxptn) { // copy dummy values for (ptn = nptn; ptn < maxptn; ptn++) memcpy(&theta_all[ptn*block], theta_all, block*sizeof(double)); } buffer_scale_all = scale_all*LOG_SCALING_THRESHOLD; } VectorClass vc_ptn[VCSIZE], vc_df[VCSIZE], vc_ddf[VCSIZE], vc_theta[VCSIZE]; VectorClass vc_unit = 1.0; VectorClass vc_freq; VectorClass df_final = 0.0, ddf_final = 0.0; // these stores values of 2 consecutive patterns VectorClass lh_ptn, df_ptn, ddf_ptn, inv_lh_ptn; // perform 2 sites at the same time for SSE/AVX efficiency #ifdef _OPENMP #pragma omp parallel private (ptn, i, j, vc_freq, vc_ptn, vc_df, vc_ddf, vc_theta, inv_lh_ptn, lh_ptn, df_ptn, ddf_ptn) { VectorClass df_final_th = 0.0; VectorClass ddf_final_th = 0.0; #pragma omp for nowait #endif for (ptn = 0; ptn < orig_nptn; ptn+=VCSIZE) { double *theta = theta_all + ptn*block; // initialization for (i = 0; i < VCSIZE; i++) { vc_theta[i].load_a(theta+i*block); vc_ptn[i] = vc_val0[0] * vc_theta[i]; vc_df[i] = vc_val1[0] * vc_theta[i]; vc_ddf[i] = vc_val2[0] * vc_theta[i]; } for (i = 1; i < block/VCSIZE; i++) { for (j = 0; j < VCSIZE; j++) { vc_theta[j].load_a(&theta[i*VCSIZE+j*block]); vc_ptn[j] = mul_add(vc_theta[j], vc_val0[i], vc_ptn[j]); vc_df[j] = mul_add(vc_theta[j], vc_val1[i], vc_df[j]); vc_ddf[j] = mul_add(vc_theta[j], vc_val2[i], vc_ddf[j]); } } lh_ptn = horizontal_add(vc_ptn) + VectorClass().load_a(&ptn_invar[ptn]); inv_lh_ptn = vc_unit / abs(lh_ptn); vc_freq.load_a(&ptn_freq[ptn]); df_ptn = horizontal_add(vc_df) * inv_lh_ptn; ddf_ptn = horizontal_add(vc_ddf) * inv_lh_ptn; ddf_ptn = nmul_add(df_ptn, df_ptn, ddf_ptn); #ifdef _OPENMP df_final_th = mul_add(df_ptn, vc_freq, df_final_th); ddf_final_th = mul_add(ddf_ptn, vc_freq, ddf_final_th); #else df_final = mul_add(df_ptn, vc_freq, df_final); ddf_final = mul_add(ddf_ptn, vc_freq, ddf_final); #endif } #ifdef _OPENMP #pragma omp critical { df_final += df_final_th; ddf_final += ddf_final_th; } } #endif df = horizontal_add(df_final); ddf = horizontal_add(ddf_final); ASSERT(!isnan(df) && !isinf(df) && "Numerical underflow for SIMD lh-derivative"); // assert(isnormal(tree_lh)); if (orig_nptn < nptn) { // ascertaiment bias correction VectorClass lh_final = 0.0; df_final = 0.0; ddf_final = 0.0; lh_ptn = 0.0; df_ptn = 0.0; ddf_ptn = 0.0; double prob_const, df_const, ddf_const; double *theta = &theta_all[orig_nptn*block]; for (ptn = orig_nptn; ptn < nptn; ptn+=VCSIZE) { lh_final += lh_ptn; df_final += df_ptn; ddf_final += ddf_ptn; // initialization for (i = 0; i < VCSIZE; i++) { vc_theta[i].load_a(theta+i*block); vc_ptn[i] = vc_val0[0] * vc_theta[i]; vc_df[i] = vc_val1[0] * vc_theta[i]; vc_ddf[i] = vc_val2[0] * vc_theta[i]; } for (i = 1; i < block/VCSIZE; i++) { for (j = 0; j < VCSIZE; j++) { vc_theta[j].load_a(&theta[i*VCSIZE+j*block]); vc_ptn[j] = mul_add(vc_theta[j], vc_val0[i], vc_ptn[j]); vc_df[j] = mul_add(vc_theta[j], vc_val1[i], vc_df[j]); vc_ddf[j] = mul_add(vc_theta[j], vc_val2[i], vc_ddf[j]); } } theta += block*VCSIZE; // ptn_invar[ptn] is not aligned lh_ptn = horizontal_add(vc_ptn) + VectorClass().load(&ptn_invar[ptn]); df_ptn = horizontal_add(vc_df); ddf_ptn = horizontal_add(vc_ddf); } switch ((nptn-orig_nptn) % VCSIZE) { case 0: prob_const = horizontal_add(lh_final+lh_ptn); df_const = horizontal_add(df_final+df_ptn); ddf_const = horizontal_add(ddf_final+ddf_ptn); break; case 1: prob_const = horizontal_add(lh_final)+lh_ptn[0]; df_const = horizontal_add(df_final)+df_ptn[0]; ddf_const = horizontal_add(ddf_final)+ddf_ptn[0]; break; case 2: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]; df_const = horizontal_add(df_final)+df_ptn[0]+df_ptn[1]; ddf_const = horizontal_add(ddf_final)+ddf_ptn[0]+ddf_ptn[1]; break; case 3: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]+lh_ptn[2]; df_const = horizontal_add(df_final)+df_ptn[0]+df_ptn[1]+df_ptn[2]; ddf_const = horizontal_add(ddf_final)+ddf_ptn[0]+ddf_ptn[1]+ddf_ptn[2]; break; default: ASSERT(0); break; } prob_const = 1.0 - prob_const; double df_frac = df_const / prob_const; double ddf_frac = ddf_const / prob_const; int nsites = aln->getNSite(); df += nsites * df_frac; ddf += nsites *(ddf_frac + df_frac*df_frac); } ASSERT(!isnan(df)); aligned_free(vc_val2); aligned_free(vc_val1); aligned_free(vc_val0); } template <class VectorClass, const int VCSIZE, const int nstates> double PhyloTree::computeLikelihoodBranchEigenSIMD(PhyloNeighbor *dad_branch, PhyloNode *dad) { PhyloNode *node = (PhyloNode*) dad_branch->node; PhyloNeighbor *node_branch = (PhyloNeighbor*) node->findNeighbor(dad); if (!central_partial_lh) initializeAllPartialLh(); if (node->isLeaf()) { PhyloNode *tmp_node = dad; dad = node; node = tmp_node; PhyloNeighbor *tmp_nei = dad_branch; dad_branch = node_branch; node_branch = tmp_nei; } if ((dad_branch->partial_lh_computed & 1) == 0) computePartialLikelihoodEigenSIMD<VectorClass, VCSIZE, nstates>(dad_branch, dad); if ((node_branch->partial_lh_computed & 1) == 0) computePartialLikelihoodEigenSIMD<VectorClass, VCSIZE, nstates>(node_branch, node); double tree_lh = node_branch->lh_scale_factor + dad_branch->lh_scale_factor; size_t ncat = site_rate->getNRate(); size_t ncat_mix = (model_factory->fused_mix_rate) ? ncat : ncat*model->getNMixtures(); size_t denom = (model_factory->fused_mix_rate) ? 1 : ncat; size_t mix_addr_nstates[ncat_mix]; size_t block = ncat_mix * nstates; size_t tip_block = nstates * model->getNMixtures(); size_t ptn; // for big data size > 4GB memory required size_t c, i, j; size_t orig_nptn = aln->size(); size_t nptn = aln->size()+model_factory->unobserved_ptns.size(); size_t maxptn = ((nptn+VCSIZE-1)/VCSIZE)*VCSIZE; maxptn = max(maxptn, aln->size()+((model_factory->unobserved_ptns.size()+VCSIZE-1)/VCSIZE)*VCSIZE); double *eval = model->getEigenvalues(); ASSERT(eval); VectorClass *vc_val = (VectorClass*)aligned_alloc<double>(block); for (c = 0; c < ncat_mix; c++) { size_t mycat = c%ncat; size_t m = c/denom; mix_addr_nstates[c] = m*nstates; double *eval_ptr = eval + mix_addr_nstates[c]; VectorClass vc_len(site_rate->getRate(mycat)*dad_branch->length); VectorClass vc_prop(site_rate->getProp(c) * model->getMixtureWeight(m)); for (i = 0; i < nstates/VCSIZE; i++) { // eval is not aligned! vc_val[c*nstates/VCSIZE+i] = exp(VectorClass().load_a(&eval_ptr[i*VCSIZE]) * vc_len) * vc_prop; } } double prob_const = 0.0; if (dad->isLeaf()) { // special treatment for TIP-INTERNAL NODE case // precompute information from one tip double *partial_lh_node = aligned_alloc<double>((aln->STATE_UNKNOWN+1)*block); IntVector states_dad = aln->seq_states[dad->id]; states_dad.push_back(aln->STATE_UNKNOWN); for (IntVector::iterator it = states_dad.begin(); it != states_dad.end(); it++) { double *lh_node = partial_lh_node + (*it)*block; double *lh_tip = tip_partial_lh + (*it)*tip_block; VectorClass *vc_val_tmp = vc_val; for (c = 0; c < ncat_mix; c++) { double *this_lh_tip = lh_tip + mix_addr_nstates[c]; for (i = 0; i < nstates; i+=VCSIZE) { (vc_val_tmp[i/VCSIZE] * VectorClass().load_a(&this_lh_tip[i])).store_a(&lh_node[i]); } lh_node += nstates; vc_val_tmp += nstates/VCSIZE; } } //VectorClass vc_tip_partial_lh[nstates]; //VectorClass vc_partial_lh_dad[VCSIZE] VectorClass vc_ptn[VCSIZE]; VectorClass lh_final(0.0), vc_freq; VectorClass lh_ptn; // store likelihoods of VCSIZE consecutive patterns int *ptn_states_dad = aligned_alloc<int>(maxptn); for (ptn = 0; ptn < orig_nptn; ptn++) ptn_states_dad[ptn] = (aln->at(ptn))[dad->id]; for (ptn = orig_nptn; ptn < nptn; ptn++) ptn_states_dad[ptn] = model_factory->unobserved_ptns[ptn-orig_nptn]; // initialize beyond #patterns for efficiency for (ptn = nptn; ptn < maxptn; ptn++) ptn_states_dad[ptn] = aln->STATE_UNKNOWN; // copy dummy values because VectorClass will access beyond nptn for (ptn = nptn; ptn < maxptn; ptn++) memcpy(&dad_branch->partial_lh[ptn*block], dad_branch->partial_lh, block*sizeof(double)); #ifdef _OPENMP #pragma omp parallel private(ptn, i, j, vc_ptn, vc_freq, lh_ptn) { VectorClass lh_final_th = 0.0; #pragma omp for nowait #endif // main loop over all patterns with a step size of VCSIZE for (ptn = 0; ptn < orig_nptn; ptn+=VCSIZE) { //double *partial_lh_dad = dad_branch->partial_lh + ptn*block; VectorClass vc_scale; for (j = 0; j < VCSIZE; j++) { vc_ptn[j] = 0.0; double *partial_lh_dad = dad_branch->partial_lh + (ptn+j)*block; UBYTE *scale_dad = dad_branch->scale_num + (ptn+j)*ncat_mix; // determine the min scaling UBYTE min_scale = *min_element(scale_dad, scale_dad+ncat_mix); vc_scale.insert(j, (double)min_scale); double *lh_node = &partial_lh_node[ptn_states_dad[ptn+j]*block]; for (c = 0; c < ncat_mix; c++) { VectorClass this_vc_ptn = 0.0; if (scale_dad[c] <= min_scale+1) { for (i = 0; i < nstates; i+=VCSIZE) { this_vc_ptn = mul_add(VectorClass().load_a(&lh_node[i]), VectorClass().load_a(&partial_lh_dad[i]), this_vc_ptn); } if (scale_dad[c] == min_scale) vc_ptn[j] += this_vc_ptn; else vc_ptn[j] += this_vc_ptn * VectorClass(SCALING_THRESHOLD); } lh_node += nstates; partial_lh_dad += nstates; } } vc_freq.load_a(&ptn_freq[ptn]); lh_ptn = horizontal_add(vc_ptn) + VectorClass().load_a(&ptn_invar[ptn]); lh_ptn = log(abs(lh_ptn)) + vc_scale*LOG_SCALING_THRESHOLD; lh_ptn.store_a(&_pattern_lh[ptn]); // multiply with pattern frequency #ifdef _OPENMP lh_final_th = mul_add(lh_ptn, vc_freq, lh_final_th); #else lh_final = mul_add(lh_ptn, vc_freq, lh_final); #endif } #ifdef _OPENMP #pragma omp critical { lh_final += lh_final_th; } } #endif tree_lh += horizontal_add(lh_final); ASSERT(!isnan(tree_lh) & !isinf(tree_lh) && "Numerical underflow for SIMD lh-branch"); // ascertainment bias correction if (orig_nptn < nptn) { lh_final = 0.0; lh_ptn = 0.0; for (ptn = orig_nptn; ptn < nptn; ptn+=VCSIZE) { // double *partial_lh_dad = &dad_branch->partial_lh[ptn*block]; VectorClass vc_scale; lh_final += lh_ptn; for (j = 0; j < VCSIZE; j++) { vc_ptn[j] = 0.0; double *partial_lh_dad = dad_branch->partial_lh + (ptn+j)*block; UBYTE *scale_dad = dad_branch->scale_num + (ptn+j)*ncat_mix; // determine the min scaling UBYTE min_scale = *min_element(scale_dad, scale_dad+ncat_mix); vc_scale.insert(j, min_scale); int state_dad = ptn_states_dad[ptn+j]; double *lh_node = &partial_lh_node[state_dad*block]; for (c = 0; c < ncat_mix; c++) { VectorClass this_vc_ptn = 0.0; if (scale_dad[c] <= min_scale+1) { for (i = 0; i < nstates; i+=VCSIZE) { this_vc_ptn = mul_add(VectorClass().load_a(&lh_node[i]), VectorClass().load_a(&partial_lh_dad[i]), this_vc_ptn); } if (scale_dad[c] == min_scale) vc_ptn[j] += this_vc_ptn; else vc_ptn[j] += this_vc_ptn * VectorClass(SCALING_THRESHOLD); } lh_node += nstates; partial_lh_dad += nstates; } // bugfix 2016-01-21, prob_const can be rescaled if (min_scale >= 1) vc_ptn[j] = vc_ptn[j] * VectorClass(SCALING_THRESHOLD); } // ptn_invar[ptn] is not aligned lh_ptn = horizontal_add(vc_ptn) + VectorClass().load(&ptn_invar[ptn]); } switch ((nptn-orig_nptn)%VCSIZE) { case 0: prob_const = horizontal_add(lh_final+lh_ptn); break; case 1: prob_const = horizontal_add(lh_final)+lh_ptn[0]; break; case 2: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]; break; case 3: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]+lh_ptn[2]; break; default: ASSERT(0); break; } } aligned_free(ptn_states_dad); aligned_free(partial_lh_node); } else { // both dad and node are internal nodes VectorClass vc_partial_lh_node[VCSIZE]; VectorClass vc_partial_lh_dad[VCSIZE], vc_ptn[VCSIZE]; VectorClass lh_final(0.0), vc_freq; VectorClass lh_ptn; // copy dummy values because VectorClass will access beyond nptn for (ptn = nptn; ptn < maxptn; ptn++) { memcpy(&dad_branch->partial_lh[ptn*block], dad_branch->partial_lh, block*sizeof(double)); memcpy(&node_branch->partial_lh[ptn*block], node_branch->partial_lh, block*sizeof(double)); } #ifdef _OPENMP #pragma omp parallel private(ptn, i, j, vc_partial_lh_node, vc_partial_lh_dad, vc_ptn, vc_freq, lh_ptn) { VectorClass lh_final_th = 0.0; #pragma omp for nowait #endif for (ptn = 0; ptn < orig_nptn; ptn+=VCSIZE) { VectorClass vc_scale; for (j = 0; j < VCSIZE; j++) { vc_ptn[j] = 0.0; double *partial_lh_dad = dad_branch->partial_lh + (ptn+j)*block; double *partial_lh_node = node_branch->partial_lh + (ptn+j)*block; VectorClass *val_tmp = vc_val; UBYTE *scale_dad = dad_branch->scale_num + (ptn+j)*ncat_mix; UBYTE *scale_node = node_branch->scale_num + (ptn+j)*ncat_mix; // determine the min scaling UBYTE sum_scale[ncat_mix]; UBYTE min_scale = sum_scale[0] = scale_dad[0]+scale_node[0]; for (c = 1; c < ncat_mix; c++) { sum_scale[c] = scale_dad[c] + scale_node[c]; min_scale = min(min_scale, sum_scale[c]); } vc_scale.insert(j, min_scale); for (c = 0; c < ncat_mix; c++) { if (sum_scale[c] <= min_scale+1) { VectorClass this_vc_ptn = 0.0; for (i = 0; i < nstates; i+=VCSIZE) { this_vc_ptn = mul_add(VectorClass().load_a(&partial_lh_node[i]) * VectorClass().load_a(&partial_lh_dad[i]), val_tmp[i/VCSIZE], this_vc_ptn); } if (sum_scale[c] == min_scale) vc_ptn[j] += this_vc_ptn; else vc_ptn[j] += this_vc_ptn * VectorClass(SCALING_THRESHOLD); } partial_lh_node += nstates; partial_lh_dad += nstates; val_tmp += nstates/VCSIZE; } } vc_freq.load_a(&ptn_freq[ptn]); lh_ptn = horizontal_add(vc_ptn) + VectorClass().load_a(&ptn_invar[ptn]); lh_ptn = log(abs(lh_ptn)) + vc_scale*LOG_SCALING_THRESHOLD; lh_ptn.store_a(&_pattern_lh[ptn]); #ifdef _OPENMP lh_final_th = mul_add(lh_ptn, vc_freq, lh_final_th); #else lh_final = mul_add(lh_ptn, vc_freq, lh_final); #endif } #ifdef _OPENMP #pragma omp critical { lh_final += lh_final_th; } } #endif tree_lh += horizontal_add(lh_final); ASSERT(!isnan(tree_lh) && !isinf(tree_lh)); if (orig_nptn < nptn) { // ascertainment bias correction lh_final = 0.0; lh_ptn = 0.0; for (ptn = orig_nptn; ptn < nptn; ptn+=VCSIZE) { lh_final += lh_ptn; VectorClass vc_scale; for (j = 0; j < VCSIZE; j++) { vc_ptn[j] = 0.0; double *partial_lh_dad = dad_branch->partial_lh + (ptn+j)*block; double *partial_lh_node = node_branch->partial_lh + (ptn+j)*block; VectorClass *val_tmp = vc_val; UBYTE *scale_dad = dad_branch->scale_num + (ptn+j)*ncat_mix; UBYTE *scale_node = node_branch->scale_num + (ptn+j)*ncat_mix; // determine the min scaling UBYTE sum_scale[ncat_mix]; UBYTE min_scale = sum_scale[0] = scale_dad[0]+scale_node[0]; for (c = 1; c < ncat_mix; c++) { sum_scale[c] = scale_dad[c] + scale_node[c]; min_scale = min(min_scale, sum_scale[c]); } vc_scale.insert(j, min_scale); for (c = 0; c < ncat_mix; c++) { if (sum_scale[c] <= min_scale+1) { VectorClass this_vc_ptn = 0.0; for (i = 0; i < nstates; i+=VCSIZE) { this_vc_ptn = mul_add(VectorClass().load_a(&partial_lh_node[i]) * VectorClass().load_a(&partial_lh_dad[i]), val_tmp[i/VCSIZE], this_vc_ptn); } if (sum_scale[c] == min_scale) vc_ptn[j] += this_vc_ptn; else vc_ptn[j] += this_vc_ptn * VectorClass(SCALING_THRESHOLD); } partial_lh_node += nstates; partial_lh_dad += nstates; val_tmp += nstates/VCSIZE; } if (min_scale >= 1) vc_ptn[j] *= VectorClass(SCALING_THRESHOLD); } /* for (j = 0; j < VCSIZE; j++) vc_ptn[j] = 0.0; for (i = 0; i < block; i+=VCSIZE) { for (j = 0; j < VCSIZE; j++) { vc_partial_lh_node[j].load_a(&partial_lh_node[i+j*block]); vc_partial_lh_dad[j].load_a(&partial_lh_dad[i+j*block]); vc_ptn[j] = mul_add(vc_val[i/VCSIZE] * vc_partial_lh_node[j], vc_partial_lh_dad[j], vc_ptn[j]); } } // bugfix 2016-01-21, prob_const can be rescaled for (j = 0; j < VCSIZE; j++) if (dad_branch->scale_num[ptn+j] + node_branch->scale_num[ptn+j] >= 1) vc_ptn[j] = vc_ptn[j] * SCALING_THRESHOLD; */ // ptn_invar[ptn] is not aligned lh_ptn = horizontal_add(vc_ptn) + VectorClass().load(&ptn_invar[ptn]); } switch ((nptn-orig_nptn)%VCSIZE) { case 0: prob_const = horizontal_add(lh_final+lh_ptn); break; case 1: prob_const = horizontal_add(lh_final)+lh_ptn[0]; break; case 2: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]; break; case 3: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]+lh_ptn[2]; break; default: ASSERT(0); break; } } } if (orig_nptn < nptn) { // ascertainment bias correction ASSERT(prob_const < 1.0 && prob_const >= 0.0); prob_const = log(1.0 - prob_const); for (ptn = 0; ptn < orig_nptn; ptn++) _pattern_lh[ptn] -= prob_const; tree_lh -= aln->getNSite()*prob_const; } aligned_free(vc_val); return tree_lh; } template <class VectorClass, const int VCSIZE, const int nstates> double PhyloTree::computeLikelihoodFromBufferEigenSIMD() { ASSERT(theta_all && theta_computed); double tree_lh = current_it->lh_scale_factor + current_it_back->lh_scale_factor; size_t ncat = site_rate->getNRate(); size_t ncat_mix = (model_factory->fused_mix_rate) ? ncat : ncat*model->getNMixtures(); size_t denom = (model_factory->fused_mix_rate) ? 1 : ncat; size_t block = ncat_mix * nstates; size_t ptn; // for big data size > 4GB memory required size_t c, i, j; size_t orig_nptn = aln->size(); size_t nptn = aln->size()+model_factory->unobserved_ptns.size(); // size_t maxptn = ((nptn+VCSIZE-1)/VCSIZE)*VCSIZE; double *eval = model->getEigenvalues(); ASSERT(eval); VectorClass *vc_val0 = (VectorClass*)aligned_alloc<double>(block); VectorClass vc_len = current_it->length; for (c = 0; c < ncat_mix; c++) { size_t m = c/denom; double *eval_ptr = eval + (m)*nstates; size_t mycat = c%ncat; VectorClass vc_rate = site_rate->getRate(mycat); VectorClass vc_prop = site_rate->getProp(mycat) * model->getMixtureWeight(m); for (i = 0; i < nstates/VCSIZE; i++) { VectorClass cof = VectorClass().load_a(&eval_ptr[i*VCSIZE]) * vc_rate; VectorClass val = exp(cof*vc_len) * vc_prop; vc_val0[c*nstates/VCSIZE+i] = val; } } VectorClass vc_ptn[VCSIZE]; VectorClass vc_freq; VectorClass lh_final = 0.0; // these stores values of 2 consecutive patterns VectorClass lh_ptn; // perform 2 sites at the same time for SSE/AVX efficiency #ifdef _OPENMP #pragma omp parallel private (ptn, i, j, vc_freq, vc_ptn, lh_ptn) { VectorClass lh_final_th = 0.0; #pragma omp for nowait #endif for (ptn = 0; ptn < orig_nptn; ptn+=VCSIZE) { double *theta = theta_all + ptn*block; // initialization for (i = 0; i < VCSIZE; i++) { vc_ptn[i] = vc_val0[0] * VectorClass().load_a(theta+i*block); } for (i = 1; i < block/VCSIZE; i++) { for (j = 0; j < VCSIZE; j++) { vc_ptn[j] = mul_add(VectorClass().load_a(&theta[i*VCSIZE+j*block]), vc_val0[i], vc_ptn[j]); } } lh_ptn = horizontal_add(vc_ptn) + VectorClass().load_a(&ptn_invar[ptn]); lh_ptn = log(abs(lh_ptn)); lh_ptn.store_a(&_pattern_lh[ptn]); vc_freq.load_a(&ptn_freq[ptn]); #ifdef _OPENMP lh_final_th = mul_add(lh_ptn, vc_freq, lh_final_th); #else lh_final = mul_add(lh_ptn, vc_freq, lh_final); #endif } #ifdef _OPENMP #pragma omp critical { lh_final += lh_final_th; } } #endif tree_lh += horizontal_add(lh_final) + buffer_scale_all; ASSERT(!isnan(tree_lh) && !isinf(tree_lh) && "Numerical underflow for SIMD lh-FromBuffer"); if (orig_nptn < nptn) { // ascertaiment bias correction lh_final = 0.0; lh_ptn = 0.0; double prob_const;// df_const, ddf_const; double *theta = &theta_all[orig_nptn*block]; UBYTE sum_scale_num[(nstates+VCSIZE)*ncat_mix]; memset(sum_scale_num, 0, sizeof(UBYTE)*(nstates+VCSIZE)); if (current_it->node->isLeaf()) memcpy(sum_scale_num, current_it_back->scale_num+orig_nptn*ncat_mix, sizeof(UBYTE)*(nptn-orig_nptn)*ncat_mix); else if (current_it_back->node->isLeaf()) memcpy(sum_scale_num, current_it->scale_num+orig_nptn*ncat_mix, sizeof(UBYTE)*(nptn-orig_nptn)*ncat_mix); else { UBYTE *cur_scale_num = current_it->scale_num + orig_nptn*ncat_mix; UBYTE *back_scale_num = current_it_back->scale_num + orig_nptn*ncat_mix; c = (nptn-orig_nptn)*ncat_mix; for (i = 0; i < c; i++) sum_scale_num[i] = cur_scale_num[i] + back_scale_num[i]; } for (ptn = orig_nptn; ptn < nptn; ptn++) { //lh_final += lh_ptn; // initialization VectorClass this_vc_ptn = vc_val0[0] * VectorClass().load_a(theta); UBYTE *this_sum_scale = sum_scale_num + (ptn-orig_nptn)*ncat_mix; UBYTE min_scale = *min_element(this_sum_scale, this_sum_scale + ncat_mix); for (i = 1; i < block/VCSIZE; i++) { this_vc_ptn = mul_add(VectorClass().load_a(&theta[i*VCSIZE]), vc_val0[i], this_vc_ptn); } theta += block; // bugfix 2016-01-21, prob_const can be rescaled if (min_scale >= 1) this_vc_ptn *= VectorClass(SCALING_THRESHOLD); // no +I for +ASC! prob_const = horizontal_add(this_vc_ptn); } /* switch ((nptn-orig_nptn) % VCSIZE) { case 0: prob_const = horizontal_add(lh_final+lh_ptn); break; case 1: prob_const = horizontal_add(lh_final)+lh_ptn[0]; break; case 2: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]; break; case 3: prob_const = horizontal_add(lh_final)+lh_ptn[0]+lh_ptn[1]+lh_ptn[2]; break; default: assert(0); break; } */ prob_const = log(1.0 - prob_const); tree_lh -= aln->getNSite() * prob_const; for (ptn = 0; ptn < orig_nptn; ptn++) _pattern_lh[ptn] -= prob_const; } aligned_free(vc_val0); return tree_lh; } /**************************************************************************** Highly optimized Parsimony function ****************************************************************************/ #ifdef _MSC_VER #define MEM_ALIGN_BEGIN __declspec(align(32)) #define MEM_ALIGN_END #else #define MEM_ALIGN_BEGIN #define MEM_ALIGN_END __attribute__((aligned(32))) #endif inline UINT fast_popcount(Vec4ui &x) { MEM_ALIGN_BEGIN UINT vec[4] MEM_ALIGN_END; x.store_a(vec); return popcount_lauradoux(vec, 4); } inline UINT fast_popcount(Vec8ui &x) { #if defined (__GNUC__) || defined(__clang__) MEM_ALIGN_BEGIN uint64_t vec[4] MEM_ALIGN_END; MEM_ALIGN_BEGIN uint64_t res[4] MEM_ALIGN_END; Vec8ui y; x.store_a(vec); __asm("popcntq %1, %0" : "=r"(res[0]) : "r"(vec[0]) : ); __asm("popcntq %1, %0" : "=r"(res[1]) : "r"(vec[1]) : ); __asm("popcntq %1, %0" : "=r"(res[2]) : "r"(vec[2]) : ); __asm("popcntq %1, %0" : "=r"(res[3]) : "r"(vec[3]) : ); y.load_a(res); return horizontal_add(y); #else MEM_ALIGN_BEGIN uint64_t vec[4] MEM_ALIGN_END; MEM_ALIGN_BEGIN int res[4] MEM_ALIGN_END; Vec4ui y; x.store_a(vec); res[0] = _mm_popcnt_u64(vec[0]); res[1] = _mm_popcnt_u64(vec[1]); res[2] = _mm_popcnt_u64(vec[2]); res[3] = _mm_popcnt_u64(vec[3]); y.load_a(res); return horizontal_add(y); #endif } inline void horizontal_popcount(Vec4ui &x) { MEM_ALIGN_BEGIN UINT vec[4] MEM_ALIGN_END; x.store_a(vec); vec[0] = vml_popcnt(vec[0]); vec[1] = vml_popcnt(vec[1]); vec[2] = vml_popcnt(vec[2]); vec[3] = vml_popcnt(vec[3]); x.load_a(vec); } inline void horizontal_popcount(Vec8ui &x) { MEM_ALIGN_BEGIN UINT vec[8] MEM_ALIGN_END; x.store_a(vec); vec[0] = vml_popcnt(vec[0]); vec[1] = vml_popcnt(vec[1]); vec[2] = vml_popcnt(vec[2]); vec[3] = vml_popcnt(vec[3]); vec[4] = vml_popcnt(vec[4]); vec[5] = vml_popcnt(vec[5]); vec[6] = vml_popcnt(vec[6]); vec[7] = vml_popcnt(vec[7]); x.load_a(vec); } template<class VectorClass> void PhyloTree::computePartialParsimonyFastSIMD(PhyloNeighbor *dad_branch, PhyloNode *dad) { if (dad_branch->partial_lh_computed & 2) return; Node *node = dad_branch->node; int nstates = aln->getMaxNumStates(); int site = 0; const int VCSIZE = VectorClass::size(); const int NUM_BITS = VectorClass::size() * UINT_BITS; dad_branch->partial_lh_computed |= 2; if (node->isLeaf() && dad) { // external node vector<Alignment*> *partitions = NULL; if (aln->isSuperAlignment()) partitions = &((SuperAlignment*)aln)->partitions; else { partitions = new vector<Alignment*>; partitions->push_back(aln); } if (aln->ordered_pattern.empty()) aln->orderPatternByNumChars(); int leafid = node->id; int pars_size = getBitsBlockSize(); memset(dad_branch->partial_pars, 0, pars_size*sizeof(UINT)); int ambi_aa[] = {2, 3, 5, 6, 9, 10}; // {4+8, 32+64, 512+1024}; UINT *x = dad_branch->partial_pars; int start_pos = 0; for (vector<Alignment*>::iterator alnit = partitions->begin(); alnit != partitions->end(); alnit++) { int end_pos = start_pos + (*alnit)->ordered_pattern.size(); switch ((*alnit)->seq_type) { case SEQ_DNA: for (int patid = start_pos; patid != end_pos; patid++) { Alignment::iterator pat = aln->ordered_pattern.begin()+ patid; int state = pat->at(leafid); int freq = pat->frequency; if (state < 4) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } x[state*VCSIZE + site/UINT_BITS] |= (1 << (site % UINT_BITS)); } } else if (state == (*alnit)->STATE_UNKNOWN) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } UINT bit1 = (1 << (site%UINT_BITS)); UINT *p = x+(site/UINT_BITS); p[0] |= bit1; p[VCSIZE] |= bit1; p[2*VCSIZE] |= bit1; p[3*VCSIZE] |= bit1; } } else { state -= 3; for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } UINT *p = x + ((site/UINT_BITS)); UINT bit1 = (1 << (site%UINT_BITS)); for (int i = 0; i < 4; i++) if (state & (1<<i)) p[i*VCSIZE] |= bit1; } } } break; case SEQ_PROTEIN: for (int patid = start_pos; patid != end_pos; patid++) { Alignment::iterator pat = aln->ordered_pattern.begin()+ patid; int state = pat->at(leafid); int freq = pat->frequency; if (state < 20) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } x[state*VCSIZE + site/UINT_BITS] |= (1 << (site % UINT_BITS)); } } else if (state == (*alnit)->STATE_UNKNOWN) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } UINT bit1 = (1 << (site%UINT_BITS)); UINT *p = x+(site/UINT_BITS); for (int i = 0; i < 20; i++) p[i*VCSIZE] |= bit1; } } else { ASSERT(state < 23); state = (state-20)*2; for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } UINT *p = x + ((site/UINT_BITS)); UINT bit1 = (1 << (site%UINT_BITS)); p[ambi_aa[state]*VCSIZE] |= bit1; p[ambi_aa[state+1]*VCSIZE] |= bit1; } } } break; default: for (int patid = start_pos; patid != end_pos; patid++) { Alignment::iterator pat = aln->ordered_pattern.begin()+ patid; int state = pat->at(leafid); int freq = pat->frequency; if (state < (*alnit)->num_states) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } x[state*VCSIZE + site/UINT_BITS] |= (1 << (site % UINT_BITS)); } } else if (state == (*alnit)->STATE_UNKNOWN) { for (int j = 0; j < freq; j++, site++) { if (site == NUM_BITS) { x += nstates*VCSIZE; site = 0; } UINT bit1 = (1 << (site%UINT_BITS)); UINT *p = x+(site/UINT_BITS); for (int i = 0; i < (*alnit)->num_states; i++) p[i*VCSIZE] |= bit1; } } else { ASSERT(0); } } break; } // end of switch start_pos = end_pos; } // of end FOR LOOP ASSERT(start_pos == aln->ordered_pattern.size()); // assert(site == aln->num_informative_sites % NUM_BITS); // add dummy states if (site > 0 && site < NUM_BITS) { x += site/UINT_BITS; *x |= ~((1<<(site%UINT_BITS)) - 1); x++; int max_sites = ((site+UINT_BITS-1)/UINT_BITS); memset(x, 255, (VCSIZE - max_sites)*sizeof(UINT)); } if (!aln->isSuperAlignment()) delete partitions; } else { // internal node ASSERT(node->degree() == 3); // it works only for strictly bifurcating tree PhyloNeighbor *left = NULL, *right = NULL; // left & right are two neighbors leading to 2 subtrees FOR_NEIGHBOR_IT(node, dad, it) { PhyloNeighbor* pit = (PhyloNeighbor*) (*it); if ((*it)->node->name != ROOT_NAME && (pit->partial_lh_computed & 2) == 0) { computePartialParsimonyFastSIMD<VectorClass>(pit, (PhyloNode*) node); } if (!left) left = pit; else right = pit; } // VectorClass score = 0; UINT score = 0; int nsites = (aln->num_informative_sites+NUM_BITS-1)/NUM_BITS; int entry_size = nstates * VCSIZE; switch (nstates) { case 4: #ifdef _OPENMP #pragma omp parallel for private (site) reduction(+: score) if(nsites>200) #endif for (site = 0; site<nsites; site++) { size_t offset = entry_size*site; VectorClass *x = (VectorClass*)(left->partial_pars + offset); VectorClass *y = (VectorClass*)(right->partial_pars + offset); VectorClass *z = (VectorClass*)(dad_branch->partial_pars + offset); z[0] = x[0] & y[0]; z[1] = x[1] & y[1]; z[2] = x[2] & y[2]; z[3] = x[3] & y[3]; VectorClass w = z[0] | z[1] | z[2] | z[3]; w = ~w; z[0] |= w & (x[0] | y[0]); z[1] |= w & (x[1] | y[1]); z[2] |= w & (x[2] | y[2]); z[3] |= w & (x[3] | y[3]); // horizontal_popcount(w); // score += w; score += fast_popcount(w); // x += 4; // y += 4; // z += 4; } break; default: #ifdef _OPENMP #pragma omp parallel for private (site) reduction(+: score) if(nsites > 800/nstates) #endif for (site = 0; site<nsites; site++) { size_t offset = entry_size*site; VectorClass *x = (VectorClass*)(left->partial_pars + offset); VectorClass *y = (VectorClass*)(right->partial_pars + offset); VectorClass *z = (VectorClass*)(dad_branch->partial_pars + offset); int i; VectorClass w = 0; for (i = 0; i < nstates; i++) { z[i] = x[i] & y[i]; w |= z[i]; } w = ~w; for (i = 0; i < nstates; i++) { z[i] |= w & (x[i] | y[i]); } // horizontal_popcount(w); // score += w; score += fast_popcount(w); x += nstates; y += nstates; z += nstates; } break; } // UINT sum_score = horizontal_add(score); // UINT *zscore = (UINT*)z; // UINT *xscore = (UINT*)x; // UINT *yscore = (UINT*)y; dad_branch->partial_pars[nstates*VCSIZE*nsites] = score + left->partial_pars[nstates*VCSIZE*nsites] + right->partial_pars[nstates*VCSIZE*nsites]; } } template<class VectorClass> int PhyloTree::computeParsimonyBranchFastSIMD(PhyloNeighbor *dad_branch, PhyloNode *dad, int *branch_subst) { PhyloNode *node = (PhyloNode*) dad_branch->node; PhyloNeighbor *node_branch = (PhyloNeighbor*) node->findNeighbor(dad); ASSERT(node_branch); if (!central_partial_pars) initializeAllPartialPars(); if ((dad_branch->partial_lh_computed & 2) == 0) computePartialParsimonyFastSIMD<VectorClass>(dad_branch, dad); if ((node_branch->partial_lh_computed & 2) == 0) computePartialParsimonyFastSIMD<VectorClass>(node_branch, node); int site; int nstates = aln->getMaxNumStates(); // VectorClass score = 0; // VectorClass w; const int NUM_BITS = VectorClass::size() * UINT_BITS; int nsites = (aln->num_informative_sites + NUM_BITS - 1)/NUM_BITS; int entry_size = nstates * VectorClass::size(); int scoreid = nsites*entry_size; UINT sum_end_node = (dad_branch->partial_pars[scoreid] + node_branch->partial_pars[scoreid]); UINT score = sum_end_node; UINT lower_bound = best_pars_score; if (branch_subst) lower_bound = INT_MAX; switch (nstates) { case 4: #ifdef _OPENMP #pragma omp parallel for private (site) reduction(+: score) if(nsites>200) #endif for (site = 0; site < nsites; site++) { size_t offset = entry_size*site; VectorClass *x = (VectorClass*)(dad_branch->partial_pars + offset); VectorClass *y = (VectorClass*)(node_branch->partial_pars + offset); VectorClass w = (x[0] & y[0]) | (x[1] & y[1]) | (x[2] & y[2]) | (x[3] & y[3]); w = ~w; // horizontal_popcount(w); // score += w; score += fast_popcount(w); #ifndef _OPENMP if (score >= lower_bound) break; #endif } break; default: #ifdef _OPENMP #pragma omp parallel for private (site) reduction(+: score) if(nsites > 800/nstates) #endif for (site = 0; site < nsites; site++) { size_t offset = entry_size*site; VectorClass *x = (VectorClass*)(dad_branch->partial_pars + offset); VectorClass *y = (VectorClass*)(node_branch->partial_pars + offset); VectorClass w = x[0] & y[0]; for (int i = 1; i < nstates; i++) { w |= x[i] & y[i]; } w = ~w; // horizontal_popcount(w); // score += w; score += fast_popcount(w); #ifndef _OPENMP if (score >= lower_bound) break; #endif } break; } // UINT sum_score = horizontal_add(score); // if (branch_subst) // *branch_subst = sum_score; if (branch_subst) *branch_subst = score - sum_end_node; // UINT *xscore = (UINT*)x; // UINT *yscore = (UINT*)y; // sum_score += *xscore + *yscore; // score += *xscore + *yscore; // return sum_score; return score; } #endif /* PHYLOKERNELSAFE_H_ */
hermv_c_dia_u_hi_trans.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif #include <memory.h> #include <stdlib.h> alphasparse_status_t ONAME(const ALPHA_Complex alpha, const ALPHA_SPMAT_DIA *A, const ALPHA_Complex *x, const ALPHA_Complex beta, ALPHA_Complex *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; const ALPHA_INT thread_num = alpha_get_thread_num(); ALPHA_Number** tmp = (ALPHA_Number**)malloc(sizeof(ALPHA_Number*) * thread_num); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(int i = 0; i < thread_num; ++i) { tmp[i] = malloc(sizeof(ALPHA_Number) * m); memset(tmp[i], 0, sizeof(ALPHA_Number) * m); } const ALPHA_INT diags = A->ndiag; #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < diags; ++i) { const ALPHA_INT threadId = alpha_get_thread_id(); const ALPHA_INT dis = A->distance[i]; if(dis > 0) { const ALPHA_INT row_start = 0; const ALPHA_INT col_start = dis; const ALPHA_INT nnz = m - dis; const ALPHA_INT start = i * A->lval; for(ALPHA_INT j = 0; j < nnz; ++j) { ALPHA_Complex v,v_c; ALPHA_Complex val_orig = A->values[start + j]; ALPHA_Complex val_conj = {A->values[start + j].real,-A->values[start + j].imag}; alpha_mul(v, alpha, val_orig); alpha_mul(v_c, alpha, val_conj); alpha_madde(tmp[threadId][col_start + j], v, x[row_start + j]); alpha_madde(tmp[threadId][row_start + j], v_c, x[col_start + j]); } } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); alpha_madde(y[i], alpha, x[i]); for(ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(y[i], y[i], tmp[j][i]); } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for (ALPHA_INT i = 0; i < thread_num; ++i) { alpha_free(tmp[i]); } alpha_free(tmp); return ALPHA_SPARSE_STATUS_SUCCESS; }
eavlDestinationTopologyPackedMapOp.h
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information. #ifndef EAVL_DESTINATION_TOPOLOGY_PACKED_MAP_OP_H #define EAVL_DESTINATION_TOPOLOGY_PACKED_MAP_OP_H #include "eavlCUDA.h" #include "eavlCellSet.h" #include "eavlCellSetExplicit.h" #include "eavlCellSetAllStructured.h" #include "eavlDataSet.h" #include "eavlArray.h" #include "eavlOpDispatch.h" #include "eavlOperation.h" #include "eavlTopology.h" #include "eavlException.h" #include <time.h> #ifdef HAVE_OPENMP #include <omp.h> #endif #ifndef DOXYGEN template <class CONN> struct eavlDestinationTopologyPackedMapOp_CPU { static inline eavlArray::Location location() { return eavlArray::HOST; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int *sparseindices = get<0>(indices).array; int ids[MAX_LOCAL_TOPOLOGY_IDS]; #pragma omp parallel for private(ids) for (int denseindex = 0; denseindex < nitems; ++denseindex) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int nids; int shapeType = conn.GetElementComponents(sparseindex, nids, ids); collect(denseindex, outputs) = functor(shapeType, nids, ids, collect(denseindex, inputs)); } } }; #if defined __CUDACC__ template <class CONN, class F, class IN, class OUT, class INDEX> __global__ void eavlDestinationTopologyPackedMapOp_kernel(int nitems, CONN conn, const IN inputs, OUT outputs, INDEX indices, F functor) { int *sparseindices = get<0>(indices).array; const int numThreads = blockDim.x * gridDim.x; const int threadID = blockIdx.x * blockDim.x + threadIdx.x; int ids[MAX_LOCAL_TOPOLOGY_IDS]; for (int denseindex = threadID; denseindex < nitems; denseindex += numThreads) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int nids; int shapeType = conn.GetElementComponents(sparseindex, nids, ids); collect(denseindex, outputs) = functor(shapeType, nids, ids, collect(denseindex, inputs)); } } template <class CONN> struct eavlDestinationTopologyPackedMapOp_GPU { static inline eavlArray::Location location() { return eavlArray::DEVICE; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int numThreads = 256; dim3 threads(numThreads, 1, 1); dim3 blocks (32, 1, 1); eavlDestinationTopologyPackedMapOp_kernel<<< blocks, threads >>>(nitems, conn, inputs, outputs, indices, functor); CUDA_CHECK_ERROR(); } }; #endif #endif // **************************************************************************** // Class: eavlDestinationTopologyPackedMapOp // // Purpose: /// Map from one element in a mesh to the same element, with /// topological information passed along to the functor. /// In this packed version of the operation, the inputs (on the destination) /// topology are sparsely indexed and the outputs are compacted, i.e. /// the outputs are densely indexed 0 to n-1. // // Programmer: Jeremy Meredith // Creation: August 1, 2013 // // Modifications: // **************************************************************************** template <class I, class O, class INDEX, class F> class eavlDestinationTopologyPackedMapOp : public eavlOperation { protected: eavlCellSet *cells; eavlTopology topology; I inputs; O outputs; INDEX indices; F functor; public: eavlDestinationTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX ind, F f) : cells(c), topology(t), inputs(i), outputs(o), indices(ind), functor(f) { } virtual void GoCPU() { eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_CPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_CPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } } virtual void GoGPU() { #ifdef HAVE_CUDA eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); conn.shapetype.NeedOnDevice(); conn.connectivity.NeedOnDevice(); conn.mapCellToIndex.NeedOnDevice(); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_GPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); conn.shapetype.NeedOnHost(); conn.connectivity.NeedOnHost(); conn.mapCellToIndex.NeedOnHost(); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_GPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } #else THROW(eavlException,"Executing GPU code without compiling under CUDA compiler."); #endif } }; // helper function for type deduction template <class I, class O, class INDEX, class F> eavlDestinationTopologyPackedMapOp<I,O,INDEX,F> *new_eavlDestinationTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX indices, F f) { return new eavlDestinationTopologyPackedMapOp<I,O,INDEX,F>(c,t,i,o,indices,f); } #endif
nr_direct.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> //#include <omp.h> #include "config.h" #include "cint.h" #include "cint_funcs.h" #include "vhf/nr_direct.h" #define MIN(I,J) ((I) < (J) ? (I) : (J)) #define MAX(I,J) ((I) > (J) ? (I) : (J)) int GTOmax_shell_dim(const int *ao_loc, const int *shls_slice, int ncenter); static int _max_cache_size(int (*intor)(), int *shls_slice, int *images_loc, int *atm, int natm, int *bas, int nbas, double *env) { int i, n; int i0 = shls_slice[0]; int i1 = shls_slice[1]; int shls[4]; int cache_size = 0; for (i = i0; i < i1; i++) { shls[0] = images_loc[i]; shls[1] = images_loc[i]; shls[2] = images_loc[i]; shls[3] = images_loc[i]; n = (*intor)(NULL, NULL, shls, atm, natm, bas, nbas, env, NULL, NULL); cache_size = MAX(cache_size, n); } return cache_size; } static int _assemble_eris(double *eri_buf, int *images_loc, int ishell, int jshell, int kshell, int lshell, double cutoff, CVHFOpt *vhfopt, IntorEnvs *envs) { int *atm = envs->atm; int *bas = envs->bas; double *env = envs->env; int natm = envs->natm; int nbas = envs->nbas; CINTOpt *cintopt = envs->cintopt; const size_t Nbas = nbas; const int *ao_loc = envs->ao_loc; const int ish0 = images_loc[ishell]; const int jsh0 = images_loc[jshell]; const int ksh0 = images_loc[kshell]; const int lsh0 = images_loc[lshell]; const int jsh1 = images_loc[jshell+1]; const int ksh1 = images_loc[kshell+1]; const int lsh1 = images_loc[lshell+1]; const int i0 = ao_loc[ishell]; const int j0 = ao_loc[jshell]; const int k0 = ao_loc[kshell]; const int l0 = ao_loc[lshell]; const int i1 = ao_loc[ishell+1]; const int j1 = ao_loc[jshell+1]; const int k1 = ao_loc[kshell+1]; const int l1 = ao_loc[lshell+1]; const int di = i1 - i0; const int dj = j1 - j0; const int dk = k1 - k0; const int dl = l1 - l0; const int dijkl = di * dj * dk * dl; double *q_cond_ijij = vhfopt->q_cond; double *q_cond_iijj = vhfopt->q_cond + Nbas*Nbas; double *q_cond_ij, *q_cond_kl, *q_cond_ik, *q_cond_jk; double *eri = eri_buf; double *bufL = eri_buf + dijkl; double *cache = bufL + dijkl; int shls[4] = {ish0}; int n, jsh, ksh, lsh; double kl_cutoff, jl_cutoff, il_cutoff; int empty = 1; for (n = 0; n < dijkl; n++) { eri[n] = 0; } q_cond_ij = q_cond_ijij + ish0 * Nbas; q_cond_ik = q_cond_iijj + ish0 * Nbas; for (jsh = jsh0; jsh < jsh1; jsh++) { if (q_cond_ij[jsh] < cutoff) { continue; } kl_cutoff = cutoff / q_cond_ij[jsh]; q_cond_jk = q_cond_iijj + jsh * Nbas; for (ksh = ksh0; ksh < ksh1; ksh++) { if (q_cond_ik[ksh] < cutoff || q_cond_jk[ksh] < cutoff) { continue; } q_cond_kl = q_cond_ijij + ksh * Nbas; jl_cutoff = cutoff / q_cond_ik[ksh]; il_cutoff = cutoff / q_cond_jk[ksh]; for (lsh = lsh0; lsh < lsh1; lsh++) { if (q_cond_kl[lsh] < kl_cutoff || q_cond_jk[lsh] < jl_cutoff || q_cond_ik[lsh] < il_cutoff) { continue; } shls[1] = jsh; shls[2] = ksh; shls[3] = lsh; if (int2e_sph(bufL, NULL, shls, atm, natm, bas, nbas, env, cintopt, cache)) { for (n = 0; n < dijkl; n++) { eri[n] += bufL[n]; } empty = 0; } } } } return !empty; } void PBCVHF_contract_k_s1(double *vk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_jk_off = dm_translation[cell_j * nkpts + cell_k]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp]; if (dm_jk_cond < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_jk_cond; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; int idm, i, jp, kp, lp, n; double sjk, qijkl; double *dm_jk; vk += cell_l * naop; for (idm = 0; idm < n_dm; idm++) { dm_jk = dms + dm_jk_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { for (jp = jp0; jp < jp1; jp++) { sjk = dm_jk[jp*naop+kp]; for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vk[i*bn+lp] += qijkl * sjk; } } } } vk += bnn; } } static void contract_k_s2_kgtl(double *vk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_jk_off = dm_translation[cell_j*nkpts+cell_k]; const int dm_jl_off = dm_translation[cell_j*nkpts+cell_l]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp]; double dm_jl_cond = vhfopt->dm_cond[dm_jl_off*nn0 + jshp*nbasp+lshp]; double dm_cond_max = MAX(dm_jk_cond, dm_jl_cond); if (dm_cond_max < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_cond_max; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; int idm, i, jp, kp, lp, n; double sjk, sjl, qijkl; double *dm_jk, *dm_jl; double *vk_ik = vk + cell_k * naop; double *vk_il = vk + cell_l * naop; for (idm = 0; idm < n_dm; idm++) { dm_jk = dms + dm_jk_off * nn + idm * knn; dm_jl = dms + dm_jl_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { for (jp = jp0; jp < jp1; jp++) { sjk = dm_jk[jp*naop+kp]; sjl = dm_jl[jp*naop+lp]; for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vk_il[i*bn+lp] += qijkl * sjk; vk_ik[i*bn+kp] += qijkl * sjl; } } } } vk_ik += bnn; vk_il += bnn; } } void PBCVHF_contract_k_s2kl(double *vk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ksh > lsh) { contract_k_s2_kgtl(vk, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } else if (ksh == lsh) { PBCVHF_contract_k_s1(vk, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } } void PBCVHF_contract_j_s1(double *vj, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp]; if (dm_lk_cond < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_lk_cond; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; int idm, i, jp, kp, lp, n; double slk, qijkl; double *dm_lk; vj += cell_j * naop; for (idm = 0; idm < n_dm; idm++) { dm_lk = dms + dm_lk_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { slk = dm_lk[lp*naop+kp]; for (jp = jp0; jp < jp1; jp++) { for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vj[i*bn+jp] += qijkl * slk; } } } } vj += bnn; } } static void contract_j_s2_kgtl(double *vj, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k]; const int dm_kl_off = dm_translation[cell_k * nkpts + cell_l]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp]; double dm_kl_cond = vhfopt->dm_cond[dm_kl_off*nn0 + kshp*nbasp+lshp]; double dm_cond_max = dm_lk_cond + dm_kl_cond; if (dm_cond_max < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_cond_max; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; int idm, i, jp, kp, lp, n; double slk, qijkl; double *dm_lk, *dm_kl; vj += cell_j * naop; for (idm = 0; idm < n_dm; idm++) { dm_lk = dms + dm_lk_off * nn + idm * knn; dm_kl = dms + dm_kl_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { slk = dm_lk[lp*naop+kp] + dm_kl[kp*naop+lp]; for (jp = jp0; jp < jp1; jp++) { for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vj[i*bn+jp] += qijkl * slk; } } } } vj += bnn; } } void PBCVHF_contract_j_s2kl(double *vj, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ksh > lsh) { contract_j_s2_kgtl(vj, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } else if (ksh == lsh) { PBCVHF_contract_j_s1(vj, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } } void PBCVHF_contract_jk_s1(double *jk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_lk_off = dm_translation[cell_l * nkpts + cell_k]; const int dm_jk_off = dm_translation[cell_j * nkpts + cell_k]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp]; double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp]; double dm_cond_max = MAX(dm_lk_cond, dm_jk_cond); if (dm_cond_max < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_cond_max; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; double *vj = jk + cell_j * naop; double *vk = jk + n_dm * bnn + cell_l * naop; int idm, i, jp, kp, lp, n; double slk, sjk, qijkl; double *dm_lk, *dm_jk; for (idm = 0; idm < n_dm; idm++) { dm_lk = dms + dm_lk_off * nn + idm * knn; dm_jk = dms + dm_jk_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { slk = dm_lk[lp*naop+kp]; for (jp = jp0; jp < jp1; jp++) { sjk = dm_jk[jp*naop+kp]; for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vj[i*bn+jp] += qijkl * slk; vk[i*bn+lp] += qijkl * sjk; } } } } vj += bnn; vk += bnn; } } static void contract_jk_s2_kgtl(double *jk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { const int cell_j = bvk_cell_id[jsh]; const int cell_k = bvk_cell_id[ksh]; const int cell_l = bvk_cell_id[lsh]; const int jshp = cell0_shl_id[jsh]; const int kshp = cell0_shl_id[ksh]; const int lshp = cell0_shl_id[lsh]; const int dm_jk_off = dm_translation[cell_j*nkpts+cell_k]; const int dm_jl_off = dm_translation[cell_j*nkpts+cell_l]; const int dm_lk_off = dm_translation[cell_l*nkpts+cell_k]; const int dm_kl_off = dm_translation[cell_k*nkpts+cell_l]; const int nn0 = nbasp * nbasp; double direct_scf_cutoff = vhfopt->direct_scf_cutoff; double dm_jk_cond = vhfopt->dm_cond[dm_jk_off*nn0 + jshp*nbasp+kshp]; double dm_jl_cond = vhfopt->dm_cond[dm_jl_off*nn0 + jshp*nbasp+lshp]; double dm_lk_cond = vhfopt->dm_cond[dm_lk_off*nn0 + lshp*nbasp+kshp]; double dm_kl_cond = vhfopt->dm_cond[dm_kl_off*nn0 + kshp*nbasp+lshp]; double dm_cond_max = MAX(dm_jk_cond, dm_jl_cond); dm_cond_max = MAX(dm_cond_max, dm_lk_cond + dm_kl_cond); if (dm_cond_max < direct_scf_cutoff) { return; } else { direct_scf_cutoff /= dm_cond_max; } if (!_assemble_eris(buf, images_loc, ish, jsh, ksh, lsh, direct_scf_cutoff, vhfopt, envs)) { return; } const int *ao_loc = envs->ao_loc; const int naop = ao_loc[nbasp]; const int nn = naop * naop; const int bn = naop * nbands; const int knn = nn * nkpts; const int bnn = bn * naop; const int i0 = ao_loc[ish]; const int jp0 = ao_loc[jshp]; const int kp0 = ao_loc[kshp]; const int lp0 = ao_loc[lshp]; const int i1 = ao_loc[ish+1]; const int jp1 = ao_loc[jshp+1]; const int kp1 = ao_loc[kshp+1]; const int lp1 = ao_loc[lshp+1]; double *vj = jk + cell_j * naop; double *vk_ik = jk + n_dm * bnn + cell_k * naop; double *vk_il = jk + n_dm * bnn + cell_l * naop; int idm, i, jp, kp, lp, n; double sjk, sjl, slk, qijkl; double *dm_jk, *dm_jl, *dm_lk, *dm_kl; for (idm = 0; idm < n_dm; idm++) { dm_lk = dms + dm_lk_off * nn + idm * knn; dm_kl = dms + dm_kl_off * nn + idm * knn; dm_jk = dms + dm_jk_off * nn + idm * knn; dm_jl = dms + dm_jl_off * nn + idm * knn; n = 0; for (lp = lp0; lp < lp1; lp++) { for (kp = kp0; kp < kp1; kp++) { slk = dm_lk[lp*naop+kp] + dm_kl[kp*naop+lp]; for (jp = jp0; jp < jp1; jp++) { sjk = dm_jk[jp*naop+kp]; sjl = dm_jl[jp*naop+lp]; for (i = i0; i < i1; i++, n++) { qijkl = buf[n]; vj[i*bn+jp] += qijkl * slk; vk_il[i*bn+lp] += qijkl * sjk; vk_ik[i*bn+kp] += qijkl * sjl; } } } } vj += bnn; vk_ik += bnn; vk_il += bnn; } } void PBCVHF_contract_jk_s2kl(double *jk, double *dms, double *buf, int n_dm, int nkpts, int nbands, int nbasp, int ish, int jsh, int ksh, int lsh, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *dm_translation, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ksh > lsh) { contract_jk_s2_kgtl(jk, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } else if (ksh == lsh) { PBCVHF_contract_jk_s1(jk, dms, buf, n_dm, nkpts, nbands, nbasp, ish, jsh, ksh, lsh, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, envs); } } /* * shls_slice refers to the shells of entire sup-mol. * bvk_ao_loc are ao_locs of bvk-cell basis appeared in supmol (some basis are removed) * nbasp is the number of basis in primitive cell * dm_translation utilizes the translation symmetry for density matrices (wrt the full bvk-cell) * DM[M,N] = DM[N-M] by mapping the 2D subscripts to 1D subscripts */ void PBCVHF_direct_drv(void (*fdot)(), double *out, double *dms, int n_dm, int nkpts, int nbands, int nbasp, char *ovlp_mask, int *bvk_cell_id, int *cell0_shl_id, int *images_loc, int *shls_slice, int *bvk_ao_loc, int *dm_translation, CINTOpt *cintopt, CVHFOpt *vhfopt, int *atm, int natm, int *bas, int nbas, double *env) { IntorEnvs envs = {natm, nbas, atm, bas, env, shls_slice, bvk_ao_loc, NULL, cintopt, 1}; const size_t ish0 = shls_slice[0]; const size_t ish1 = shls_slice[1]; const size_t jsh0 = shls_slice[2]; const size_t jsh1 = shls_slice[3]; const size_t ksh0 = shls_slice[4]; const size_t ksh1 = shls_slice[5]; const size_t lsh0 = shls_slice[6]; const size_t lsh1 = shls_slice[7]; const size_t nish = ish1 - ish0; const size_t njsh = jsh1 - jsh0; const size_t nksh = ksh1 - ksh0; const size_t nlsh = lsh1 - lsh0; const int di = GTOmax_shell_dim(bvk_ao_loc, shls_slice, 1); const int cache_size = _max_cache_size(int2e_sph, shls_slice, images_loc, atm, natm, bas, nbas, env); const size_t nij = nish * njsh; const int naop = bvk_ao_loc[nbasp]; #pragma omp parallel { size_t ij, n; int i, j, k, l; size_t size = n_dm * naop * naop * nbands; if (fdot == &PBCVHF_contract_jk_s2kl || fdot == &PBCVHF_contract_jk_s1) { size *= 2; // vj and vk } double *v_priv = calloc(size, sizeof(double)); double *buf = malloc(sizeof(double) * (di*di*di*di*2 + cache_size)); #pragma omp for schedule(dynamic, 1) for (ij = 0; ij < nij; ij++) { i = ij / njsh; j = ij % njsh; if (!ovlp_mask[i*njsh+j]) { continue; } for (k = 0; k < nksh; k++) { for (l = 0; l < nlsh; l++) { if (!ovlp_mask[k*nlsh+l]) { continue; } (*fdot)(v_priv, dms, buf, n_dm, nkpts, nbands, nbasp, i, j, k, l, bvk_cell_id, cell0_shl_id, images_loc, dm_translation, vhfopt, &envs); } } } #pragma omp critical { for (n = 0; n < size; n++) { out[n] += v_priv[n]; } } free(buf); free(v_priv); } } /************************************************/ void CVHFset_int2e_q_cond(int (*intor)(), CINTOpt *cintopt, double *q_cond, int *ao_loc, int *atm, int natm, int *bas, int nbas, double *env); static int _int2e_swap_jk(double *buf, int *dims, int *shls, int *atm, int natm, int *bas, int nbas, double *env, CINTOpt *cintopt, double *cache) { int shls_swap_jk[4] = {shls[0], shls[2], shls[1], shls[3]}; return int2e_sph(buf, dims, shls_swap_jk, atm, natm, bas, nbas, env, cintopt, cache); } void PBCVHFsetnr_direct_scf(CVHFOpt *opt, int (*intor)(), CINTOpt *cintopt, int *ao_loc, int *atm, int natm, int *bas, int nbas, double *env) { /* This memory is released in void CVHFdel_optimizer, Don't know * why valgrind raises memory leak here */ if (opt->q_cond) { free(opt->q_cond); } // nbas in the input arguments may different to opt->nbas. // Use opt->nbas because it is used in the prescreen function nbas = opt->nbas; size_t Nbas = nbas; opt->q_cond = (double *)malloc(sizeof(double) * Nbas * Nbas * 2); double *qcond_ijij = opt->q_cond; double *qcond_iijj = qcond_ijij + Nbas * Nbas; CVHFset_int2e_q_cond(intor, cintopt, qcond_ijij, ao_loc, atm, natm, bas, nbas, env); CVHFset_int2e_q_cond(_int2e_swap_jk, cintopt, qcond_iijj, ao_loc, atm, natm, bas, nbas, env); }
convolution_sgemm_int8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void im2col_sgemm_int8_msa(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Option& opt) { // Mat bottom_im2col(size, maxk, inch, 8u, 8, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; // permute Mat tmp; #if __mips_msa if (inch >= 4) { if (size >= 2) tmp.create(2 * maxk, inch / 4 + inch % 4, size / 2 + size % 2, 4u, 4, opt.workspace_allocator); else tmp.create(maxk, inch / 4 + inch % 4, size, 4u, 4, opt.workspace_allocator); } else { if (size >= 2) tmp.create(2 * maxk, inch, size / 2 + size % 2, 1u, 1, opt.workspace_allocator); else tmp.create(maxk, inch, size, 1u, 1, opt.workspace_allocator); } { int remain_size_start = 0; int nn_size = (size - remain_size_start) >> 1; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = remain_size_start + ii * 2; signed char* tmpptr = tmp.channel(i / 2); int q = 0; for (; q + 3 < inch; q += 4) { const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i; const signed char* img1 = (const signed char*)bottom_im2col.channel(q + 1) + i; const signed char* img2 = (const signed char*)bottom_im2col.channel(q + 2) + i; const signed char* img3 = (const signed char*)bottom_im2col.channel(q + 3) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img2[0]; tmpptr[3] = img3[0]; tmpptr[4] = img0[1]; tmpptr[5] = img1[1]; tmpptr[6] = img2[1]; tmpptr[7] = img3[1]; tmpptr += 8; img0 += size; img1 += size; img2 += size; img3 += size; } } for (; q < inch; q++) { const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr += 2; img0 += size; } } } remain_size_start += nn_size << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { signed char* tmpptr = tmp.channel(i / 2 + i % 2); int q = 0; for (; q + 3 < inch; q += 4) { const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i; const signed char* img1 = (const signed char*)bottom_im2col.channel(q + 1) + i; const signed char* img2 = (const signed char*)bottom_im2col.channel(q + 2) + i; const signed char* img3 = (const signed char*)bottom_im2col.channel(q + 3) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img2[0]; tmpptr[3] = img3[0]; tmpptr += 4; img0 += size; img1 += size; img2 += size; img3 += size; } } for (; q < inch; q++) { const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += size; } } } } #else // __mips_msa tmp.create(maxk, inch, size, 1u, 1, opt.workspace_allocator); { #pragma omp parallel for num_threads(opt.num_threads) for (int i = 0; i < size; i++) { signed char* tmpptr = tmp.channel(i); int q = 0; for (; q < inch; q++) { const signed char* img0 = (const signed char*)bottom_im2col.channel(q) + i; for (int k = 0; k < maxk; k++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += size; } } } } #endif // __mips_msa int nn_outch = 0; int remain_outch_start = 0; #if __mips_msa nn_outch = 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 + 1 < size; i += 2) { const signed char* tmpptr = tmp.channel(i / 2); const signed char* kptr = kernel.channel(p / 4); int nn4 = (inch / 4) * maxk; int nn1 = (inch % 4) * maxk; v4i32 _sum00 = __msa_fill_w(0); v4i32 _sum10 = __msa_fill_w(0); if (nn4 > 0) { v4i32 _sum01 = __msa_fill_w(0); v4i32 _sum02 = __msa_fill_w(0); v4i32 _sum03 = __msa_fill_w(0); v4i32 _sum11 = __msa_fill_w(0); v4i32 _sum12 = __msa_fill_w(0); v4i32 _sum13 = __msa_fill_w(0); int j = 0; for (; j < nn4; j++) { v16i8 _val = __msa_ld_b(tmpptr, 0); v8i16 _val01 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_val, 0), _val); v8i16 _val0 = (v8i16)__msa_ilvr_d((v2i64)_val01, (v2i64)_val01); v8i16 _val1 = (v8i16)__msa_ilvl_d((v2i64)_val01, (v2i64)_val01); v16i8 _w01 = __msa_ld_b(kptr, 0); v16i8 _extw01 = __msa_clti_s_b(_w01, 0); v8i16 _w0 = (v8i16)__msa_ilvr_b(_extw01, _w01); v8i16 _w1 = (v8i16)__msa_ilvl_b(_extw01, _w01); v8i16 _s00 = __msa_mulv_h(_val0, _w0); v8i16 _s01 = __msa_mulv_h(_val0, _w1); v8i16 _s10 = __msa_mulv_h(_val1, _w0); v8i16 _s11 = __msa_mulv_h(_val1, _w1); v8i16 _exts00 = __msa_clti_s_h(_s00, 0); v8i16 _exts01 = __msa_clti_s_h(_s01, 0); v8i16 _exts10 = __msa_clti_s_h(_s10, 0); v8i16 _exts11 = __msa_clti_s_h(_s11, 0); v4i32 _s00l = (v4i32)__msa_ilvr_h(_exts00, _s00); v4i32 _s00h = (v4i32)__msa_ilvl_h(_exts00, _s00); v4i32 _s01l = (v4i32)__msa_ilvr_h(_exts01, _s01); v4i32 _s01h = (v4i32)__msa_ilvl_h(_exts01, _s01); v4i32 _s10l = (v4i32)__msa_ilvr_h(_exts10, _s10); v4i32 _s10h = (v4i32)__msa_ilvl_h(_exts10, _s10); v4i32 _s11l = (v4i32)__msa_ilvr_h(_exts11, _s11); v4i32 _s11h = (v4i32)__msa_ilvl_h(_exts11, _s11); _sum00 = __msa_addv_w(_sum00, _s00l); _sum01 = __msa_addv_w(_sum01, _s00h); _sum02 = __msa_addv_w(_sum02, _s01l); _sum03 = __msa_addv_w(_sum03, _s01h); _sum10 = __msa_addv_w(_sum10, _s10l); _sum11 = __msa_addv_w(_sum11, _s10h); _sum12 = __msa_addv_w(_sum12, _s11l); _sum13 = __msa_addv_w(_sum13, _s11h); tmpptr += 8; kptr += 16; } // transpose 4x4 { v4i32 _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = __msa_ilvr_w(_sum01, _sum00); _tmp1 = __msa_ilvr_w(_sum03, _sum02); _tmp2 = __msa_ilvl_w(_sum01, _sum00); _tmp3 = __msa_ilvl_w(_sum03, _sum02); _sum00 = (v4i32)__msa_ilvr_d((v2i64)_tmp1, (v2i64)_tmp0); _sum01 = (v4i32)__msa_ilvl_d((v2i64)_tmp1, (v2i64)_tmp0); _sum02 = (v4i32)__msa_ilvr_d((v2i64)_tmp3, (v2i64)_tmp2); _sum03 = (v4i32)__msa_ilvl_d((v2i64)_tmp3, (v2i64)_tmp2); } { v4i32 _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = __msa_ilvr_w(_sum11, _sum10); _tmp1 = __msa_ilvr_w(_sum13, _sum12); _tmp2 = __msa_ilvl_w(_sum11, _sum10); _tmp3 = __msa_ilvl_w(_sum13, _sum12); _sum10 = (v4i32)__msa_ilvr_d((v2i64)_tmp1, (v2i64)_tmp0); _sum11 = (v4i32)__msa_ilvl_d((v2i64)_tmp1, (v2i64)_tmp0); _sum12 = (v4i32)__msa_ilvr_d((v2i64)_tmp3, (v2i64)_tmp2); _sum13 = (v4i32)__msa_ilvl_d((v2i64)_tmp3, (v2i64)_tmp2); } _sum00 = __msa_addv_w(_sum00, _sum01); _sum02 = __msa_addv_w(_sum02, _sum03); _sum10 = __msa_addv_w(_sum10, _sum11); _sum12 = __msa_addv_w(_sum12, _sum13); _sum00 = __msa_addv_w(_sum00, _sum02); _sum10 = __msa_addv_w(_sum10, _sum12); } int j = 0; for (; j < nn1; j++) { v8i16 _val0 = __msa_fill_h(tmpptr[0]); v8i16 _val1 = __msa_fill_h(tmpptr[1]); v8i16 _val = (v8i16)__msa_ilvr_d((v2i64)_val1, (v2i64)_val0); v16i8 _w = __msa_ld_b(kptr, 0); v8i16 _w16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_w, 0), _w); _w16 = (v8i16)__msa_ilvr_d((v2i64)_w16, (v2i64)_w16); v8i16 _s0 = __msa_mulv_h(_val, _w16); v8i16 _exts0 = __msa_clti_s_h(_s0, 0); v4i32 _s0l = (v4i32)__msa_ilvr_h(_exts0, _s0); v4i32 _s0h = (v4i32)__msa_ilvl_h(_exts0, _s0); _sum00 = __msa_addv_w(_sum00, _s0l); _sum10 = __msa_addv_w(_sum10, _s0h); tmpptr += 2; kptr += 4; } int sum[8]; __msa_st_w(_sum00, sum, 0); __msa_st_w(_sum10, sum + 4, 0); outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr0[1] = sum[4]; outptr1[1] = sum[5]; outptr2[1] = sum[6]; outptr3[1] = sum[7]; outptr0 += 2; outptr1 += 2; outptr2 += 2; outptr3 += 2; } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 2 + i % 2); const signed char* kptr = kernel.channel(p / 4); int nn4 = (inch / 4) * maxk; int nn1 = (inch % 4) * maxk; v4i32 _sum0 = __msa_fill_w(0); if (nn4 > 0) { v4i32 _sum1 = __msa_fill_w(0); v4i32 _sum2 = __msa_fill_w(0); v4i32 _sum3 = __msa_fill_w(0); int j = 0; for (; j < nn4; j++) { v16i8 _val = __msa_ld_b(tmpptr, 0); v8i16 _val16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_val, 0), _val); _val16 = (v8i16)__msa_ilvr_d((v2i64)_val16, (v2i64)_val16); v16i8 _w01 = __msa_ld_b(kptr, 0); v16i8 _extw01 = __msa_clti_s_b(_w01, 0); v8i16 _w0 = (v8i16)__msa_ilvr_b(_extw01, _w01); v8i16 _w1 = (v8i16)__msa_ilvl_b(_extw01, _w01); v8i16 _s0 = __msa_mulv_h(_val16, _w0); v8i16 _s1 = __msa_mulv_h(_val16, _w1); v8i16 _exts0 = __msa_clti_s_h(_s0, 0); v8i16 _exts1 = __msa_clti_s_h(_s1, 0); v4i32 _s0l = (v4i32)__msa_ilvr_h(_exts0, _s0); v4i32 _s0h = (v4i32)__msa_ilvl_h(_exts0, _s0); v4i32 _s1l = (v4i32)__msa_ilvr_h(_exts1, _s1); v4i32 _s1h = (v4i32)__msa_ilvl_h(_exts1, _s1); _sum0 = __msa_addv_w(_sum0, _s0l); _sum1 = __msa_addv_w(_sum1, _s0h); _sum2 = __msa_addv_w(_sum2, _s1l); _sum3 = __msa_addv_w(_sum3, _s1h); tmpptr += 4; kptr += 16; } // transpose 4x4 { v4i32 _tmp0, _tmp1, _tmp2, _tmp3; _tmp0 = __msa_ilvr_w(_sum1, _sum0); _tmp1 = __msa_ilvr_w(_sum3, _sum2); _tmp2 = __msa_ilvl_w(_sum1, _sum0); _tmp3 = __msa_ilvl_w(_sum3, _sum2); _sum0 = (v4i32)__msa_ilvr_d((v2i64)_tmp1, (v2i64)_tmp0); _sum1 = (v4i32)__msa_ilvl_d((v2i64)_tmp1, (v2i64)_tmp0); _sum2 = (v4i32)__msa_ilvr_d((v2i64)_tmp3, (v2i64)_tmp2); _sum3 = (v4i32)__msa_ilvl_d((v2i64)_tmp3, (v2i64)_tmp2); } _sum0 = __msa_addv_w(_sum0, _sum1); _sum2 = __msa_addv_w(_sum2, _sum3); _sum0 = __msa_addv_w(_sum0, _sum2); } int j = 0; for (; j < nn1; j++) { v8i16 _val = __msa_fill_h(tmpptr[0]); v16i8 _w = __msa_ld_b(kptr, 0); v8i16 _w16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_w, 0), _w); v8i16 _s0 = __msa_mulv_h(_val, _w16); v4i32 _s032 = (v4i32)__msa_ilvr_h(__msa_clti_s_h(_s0, 0), _s0); _sum0 = __msa_addv_w(_sum0, _s032); tmpptr += 1; kptr += 4; } int sum[4]; __msa_st_w(_sum0, sum, 0); outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr0 += 1; outptr1 += 1; outptr2 += 1; outptr3 += 1; } } remain_outch_start += nn_outch << 2; #endif // __mips_msa #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { int* outptr0 = top_blob.channel(p); int i = 0; #if __mips_msa for (; i + 1 < size; i += 2) { const signed char* tmpptr = tmp.channel(i / 2); const signed char* kptr = kernel.channel(p / 4 + p % 4); int nn4 = (inch / 4) * maxk; int nn1 = (inch % 4) * maxk; int sum0 = 0; int sum1 = 0; if (nn4 > 0) { v4i32 _sum0 = __msa_fill_w(0); v4i32 _sum1 = __msa_fill_w(0); int j = 0; for (; j < nn4; j++) { v16i8 _val = __msa_ld_b(tmpptr, 0); v8i16 _val16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_val, 0), _val); v16i8 _w = __msa_ld_b(kptr, 0); v8i16 _w16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_w, 0), _w); _w16 = (v8i16)__msa_ilvr_d((v2i64)_w16, (v2i64)_w16); v8i16 _s0 = __msa_mulv_h(_val16, _w16); v8i16 _exts0 = __msa_clti_s_h(_s0, 0); v4i32 _s0l = (v4i32)__msa_ilvr_h(_exts0, _s0); v4i32 _s0h = (v4i32)__msa_ilvl_h(_exts0, _s0); _sum0 = __msa_addv_w(_sum0, _s0l); _sum1 = __msa_addv_w(_sum1, _s0h); tmpptr += 8; kptr += 4; } sum0 = _sum0[0] + _sum0[1] + _sum0[2] + _sum0[3]; sum1 = _sum1[0] + _sum1[1] + _sum1[2] + _sum1[3]; } int j = 0; for (; j < nn1; j++) { signed char val0 = tmpptr[0]; signed char val1 = tmpptr[1]; signed char w = kptr[0]; sum0 += val0 * w; sum1 += val1 * w; tmpptr += 2; kptr += 1; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0 += 2; } for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i / 2 + i % 2); const signed char* kptr = kernel.channel(p / 4 + p % 4); int nn4 = (inch / 4) * maxk; int nn1 = (inch % 4) * maxk; int sum = 0; if (nn4 > 0) { v4i32 _sum = __msa_fill_w(0); int j = 0; for (; j < nn4; j++) { v16i8 _val = __msa_ld_b(tmpptr, 0); v8i16 _val16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_val, 0), _val); v16i8 _w = __msa_ld_b(kptr, 0); v8i16 _w16 = (v8i16)__msa_ilvr_b(__msa_clti_s_b(_w, 0), _w); v8i16 _s0 = __msa_mulv_h(_val16, _w16); v4i32 _s032 = (v4i32)__msa_ilvr_h(__msa_clti_s_h(_s0, 0), _s0); _sum = __msa_addv_w(_sum, _s032); tmpptr += 4; kptr += 4; } sum = _sum[0] + _sum[1] + _sum[2] + _sum[3]; } int j = 0; for (; j < nn1; j++) { signed char val = tmpptr[0]; signed char w = kptr[0]; sum += val * w; tmpptr += 1; kptr += 1; } outptr0[0] = sum; outptr0 += 1; } #else // __mips_msa for (; i < size; i++) { const signed char* tmpptr = tmp.channel(i); const signed char* kptr = kernel.channel(p); int nn1 = inch * maxk; int sum = 0; int j = 0; for (; j < nn1; j++) { signed char val = tmpptr[0]; signed char w = kptr[0]; sum += val * w; tmpptr += 1; kptr += 1; } outptr0[0] = sum; outptr0 += 1; } #endif // __mips_msa } } static void convolution_im2col_sgemm_transform_kernel_int8_msa(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; #if __mips_msa // interleave // src = maxk-inch-outch // dst = 4a-4b-maxk-inch/4a-outch/4b Mat kernel = _kernel.reshape(maxk, inch, outch); if (outch >= 4) { if (inch >= 4) kernel_tm.create(16 * maxk, inch / 4 + inch % 4, outch / 4 + outch % 4, (size_t)1u); else kernel_tm.create(4 * maxk, inch, outch / 4 + outch % 4, (size_t)1u); } else { if (inch >= 4) kernel_tm.create(4 * maxk, inch / 4 + inch % 4, outch, (size_t)1u); else kernel_tm.create(1 * maxk, inch, outch, (size_t)1u); } int q = 0; for (; q + 3 < outch; q += 4) { signed char* g00 = kernel_tm.channel(q / 4); int p = 0; for (; p + 3 < inch; p += 4) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { const signed char* k00 = kernel.channel(q + i).row<const signed char>(p + j); g00[0] = k00[k]; g00++; } } } } for (; p < inch; p++) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 4; i++) { const signed char* k00 = kernel.channel(q + i).row<const signed char>(p); g00[0] = k00[k]; g00++; } } } } // TODO unroll 2 for (; q < outch; q++) { signed char* g00 = kernel_tm.channel(q / 4 + q % 4); int p = 0; for (; p + 3 < inch; p += 4) { for (int k = 0; k < maxk; k++) { for (int j = 0; j < 4; j++) { const signed char* k00 = kernel.channel(q).row<const signed char>(p + j); g00[0] = k00[k]; g00++; } } } for (; p < inch; p++) { for (int k = 0; k < maxk; k++) { const signed char* k00 = kernel.channel(q).row<const signed char>(p); g00[0] = k00[k]; g00++; } } } #else // __mips_msa kernel_tm = _kernel.reshape(maxk, inch, outch); #endif // __mips_msa } static void convolution_im2col_sgemm_int8_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 1u, 1, opt.workspace_allocator); { const int gap = w * stride_h - outw * stride_w; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); signed char* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const signed char* sptr = img.row<const signed char>(dilation_h * u) + dilation_w * v; for (int i = 0; i < outh; i++) { int j = 0; for (; j + 3 < outw; j += 4) { ptr[0] = sptr[0]; ptr[1] = sptr[stride_w]; ptr[2] = sptr[stride_w * 2]; ptr[3] = sptr[stride_w * 3]; sptr += stride_w * 4; ptr += 4; } for (; j + 1 < outw; j += 2) { ptr[0] = sptr[0]; ptr[1] = sptr[stride_w]; sptr += stride_w * 2; ptr += 2; } for (; j < outw; j++) { ptr[0] = sptr[0]; sptr += stride_w; ptr += 1; } sptr += gap; } } } } } im2col_sgemm_int8_msa(bottom_im2col, top_blob, kernel, opt); }
omp_ex_03.c
#include <stdio.h> #include <omp.h> /* MIT License Copyright (c) 2019 NOUREDDINE DAGHBOUDJ 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. */ int main() { #pragma omp parallel { // Returns the current number of threads printf("Number of Threads: %i\n", omp_get_num_threads()); } return 0; }
mmap_recv.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <unistd.h> #include <string.h> int main() { int threads = 4; size_t size = threads * 2048*2048; int fd = open("/tmp/testmmap", O_RDWR); volatile char *buf = (char*)mmap(NULL, 4096 + size, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); char *dst = (char*)malloc(size); for (size_t i = 0; i < size; i++) { dst[i] = 0xff & i; } #pragma omp parallel for for (size_t i = 0; i < threads; i++) { size_t off = i * size/threads; size_t k = 0; size_t res = 0; for (int j = 0; j < 1e2; j++) { while (buf[i] == 1) { k = (k + 1) % (size / threads); res ^= dst[off+k] ^ j; } // printf("recv %zd, %d\n", i, j); // memcpy(buf+4096, src, size); memcpy(dst+off, buf+(off+4096), size/threads); buf[i] = 1; } printf("%zd: %zd\n", i, res); } ftruncate(fd, 0); return 0; }
main.c
int bar() { return 10; }; void foo(int N, double *A) { int X, Y; #pragma omp parallel default(shared) { #pragma omp for private(X, Y) for (int I = 0; I < N; ++I) { X = I; if (I > N) { Y = bar(); X = X + Y + 1; } A[I] = X; } } }
libvoodoo.c
#include <stdlib.h> #include <stdio.h> #include <inttypes.h> #include <omp.h> #include <math.h> __attribute__((target(mic))) void voodoo(double* a, double* b, double* c, int nelem, int device, int offload) { int mthreads; #pragma offload target(mic:device) if(offload) { mthreads = omp_get_max_threads(); } const int64_t nworkers = nelem > mthreads ? mthreads : 1; const int64_t work_split= nelem / nworkers; const int64_t work_spill= nelem % nworkers; #pragma offload \ target(mic:device) \ in(a:length(0) alloc_if(0) free_if(0)), \ in(b:length(0) alloc_if(0) free_if(0)), \ in(c:length(0) alloc_if(0) free_if(0)) \ in(work_split) \ in(work_spill) \ if(offload) { #pragma omp parallel num_threads(nworkers) { for(int i=0; i<100; ++i) { const int tid = omp_get_thread_num(); int64_t work=0, work_offset=0, work_end=0; if (tid < work_spill) { work = work_split + 1; work_offset = tid * work; } else { work = work_split; work_offset = tid * work + work_spill; } work_end = work_offset + work; if (work) { for (int eidx=work_offset; eidx<work_end; ++eidx) { c[eidx] = ((a[eidx] + b[eidx]) / 100.0); } } } } } }
bert_layer_mb1_dynamic_tokens.h
#ifndef BERT_LAYER_H_ #define BERT_LAYER_H_ #include <new> #include <string> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <math.h> #include <mkl.h> #include <omp.h> #include <iostream> #include <immintrin.h> #include "my_types.h" //#include "timer.h" class BertLayer { public: // intermediateSize 3072 feed-forward/filter size 升维维度 4*hiddensize BertLayer(int layerIdx, int maxTokenSize = 128, int hiddenSize = 768, int intermediateSize = 3072) { this->layerIdx = layerIdx; this->maxTokenSize = maxTokenSize; this->hiddenSize = hiddenSize; this->intermediateSize = intermediateSize; qkvMatMul.Resize(maxTokenSize, hiddenSize*3); resultBuffer1.Resize(maxTokenSize, hiddenSize); resultBuffer2.Resize(maxTokenSize, hiddenSize); intermediateBuffer.Resize(maxTokenSize, intermediateSize); for (int i = 0; i < 12; ++i) { qk_result[i] = (float *)aligned_alloc(64, sizeof(float) * maxTokenSize * maxTokenSize); exp_buffer[i] = (float *)aligned_alloc(64, sizeof(float) * maxTokenSize); } magic_value = (float *)aligned_alloc(64, sizeof(float) * maxTokenSize); int mkl_num_threads = mkl_get_max_threads(); #pragma omp parallel { int tid = omp_get_thread_num(); if (tid == 0) { num_threads = omp_get_num_threads(); } } if (mkl_num_threads != num_threads) { printf("WARNING: mkl_num_threads=%d, omp_num_threads=%d\n", mkl_num_threads, num_threads); } #ifndef __INTEL_COMPILER erf_buffer = new float * [num_threads]; for (int i = 0; i < num_threads; ++i) { erf_buffer[i] = (float *)aligned_alloc(64, sizeof(float) * intermediateSize); } #endif } virtual ~BertLayer() { for (int i = 0; i < 12; ++i) { free(qk_result[i]); free(exp_buffer[i]); qk_result[i] = NULL; exp_buffer[i] = NULL; } free(magic_value); magic_value = NULL; #ifndef __INTEL_COMPILER for (int i = 0; i < num_threads; ++i) { free(erf_buffer[i]); } delete[] erf_buffer; erf_buffer = NULL; #endif } void setWeights(const float *_queryWeight, const float *_queryBias, const float *_keyWeight, const float *_keyBias, const float *_valueWeight, const float *_valueBias, const float *_attentionOutputWeight, const float *_attentionOutputBias, const float *_gamma1, const float *_beta1, const float *_intermediateWeight, const float *_intermediateBias, const float *_outputWeight, const float *_outputBias, const float *_gamma2, const float *_beta2) { // Merged weights, dimension is like: 768*(768*3) hpj::Matrix<float> tmp; tmp.Resize(hiddenSize, hiddenSize * 3); copyWeights(tmp, 0, hiddenSize, _queryWeight); copyWeights(tmp, hiddenSize, hiddenSize*2, _keyWeight); copyWeights(tmp, hiddenSize*2, hiddenSize*3, _valueWeight); copyTransposed(qkvWeight, tmp); /* qkvWeight.Resize(hiddenSize, hiddenSize * 3); copyWeights(qkvWeight, 0, hiddenSize, _queryWeight); copyWeights(qkvWeight, hiddenSize, hiddenSize*2, _keyWeight); copyWeights(qkvWeight, hiddenSize*2, hiddenSize*3, _valueWeight); */ // Merged bias qkvBias.Resize(hiddenSize * 3); memcpy(qkvBias.Data(), _queryBias, sizeof(float) * hiddenSize); memcpy(qkvBias.Data() + hiddenSize, _keyBias, sizeof(float) * hiddenSize); memcpy(qkvBias.Data() + hiddenSize*2, _valueBias, sizeof(float) * hiddenSize); // Weights for attention output attentionOutputWeight.Resize(hiddenSize, hiddenSize); copyWeights(attentionOutputWeight, _attentionOutputWeight); attentionOutputBias.Resize(hiddenSize); memcpy(attentionOutputBias.Data(), _attentionOutputBias, sizeof(float) * hiddenSize); // gamma and beta for batchnorm after self attention gamma1.Resize(hiddenSize); beta1.Resize(hiddenSize); memcpy(gamma1.Data(), _gamma1, sizeof(float) * hiddenSize); memcpy(beta1.Data(), _beta1, sizeof(float) * hiddenSize); // intermediate weight and bias intermediateWeight.Resize(hiddenSize, intermediateSize); copyWeights(intermediateWeight, _intermediateWeight); intermediateBias.Resize(intermediateSize); memcpy(intermediateBias.Data(), _intermediateBias, sizeof(float) * intermediateSize); // output dense weight and bias outputWeight.Resize(intermediateSize, hiddenSize); copyWeights(outputWeight, _outputWeight); outputBias.Resize(hiddenSize); memcpy(outputBias.Data(), _outputBias, sizeof(float) * hiddenSize); // gamma and beta for the last batchnorm gamma2.Resize(hiddenSize); beta2.Resize(hiddenSize); memcpy(gamma2.Data(), _gamma2, sizeof(float) * hiddenSize); memcpy(beta2.Data(), _beta2, sizeof(float) * hiddenSize); } // Do the forward computing for the whole BERT layer // input: inputTokenSize x hidden_size // actualTokens: #tokens = inputTokenSize - padded_tokens hpj::Matrix<float> &forward(hpj::Matrix<float> &inputBuffer, int inputTokens, int actualTokens) { this->inputTokenSize = inputTokens; // Query, Key, Value computed together sgemm(inputBuffer, qkvWeight, qkvMatMul); biasAdd(qkvMatMul, qkvBias); //dumpMatrix(qkvMatMul); // BatchMatMul hpj::Matrix<float> query(qkvMatMul, 0, inputTokenSize, 0, hiddenSize); hpj::Matrix<float> key(qkvMatMul, 0, inputTokenSize, hiddenSize, hiddenSize); hpj::Matrix<float> value(qkvMatMul, 0, inputTokenSize, hiddenSize*2, hiddenSize); batchMatMul(query, key, qk_result); //printf("qk_result[0]=%f,%f\n", qk_result[0][0], qk_result[0][1]); // Softmax computeSoftmax(actualTokens); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/self/Softmax:\n", layerIdx); printf("%f, %f, ...\n", qk_result[0][0], qk_result[0][1]); printf("%f, %f, ...\n", qk_result[1][0], qk_result[1][1]); #endif // BatchMatMul batchMatMul(qk_result, value, resultBuffer1); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/self/Reshape_3:\n", layerIdx); dumpMatrix(resultBuffer1); #endif // dense denseWithSum(resultBuffer1, attentionOutputWeight, attentionOutputBias, inputBuffer, resultBuffer2); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/output/add:\n", layerIdx); dumpMatrix(resultBuffer2); #endif // batchmorm batchnorm(resultBuffer2, gamma1, beta1); #ifdef DEBUG printf("bert/encoder/layer_%d/attention/output/LayerNorm/batchnorm/add_1:\n", layerIdx); dumpMatrix(resultBuffer2); #endif // intermediate intermediate(resultBuffer2, intermediateBuffer); #ifdef DEBUG printf("intermediate(bert/encoder/layer_%d/intermediate/dense/mul_1):\n", layerIdx); dumpMatrix(intermediateBuffer); #endif // dense in output denseWithSum(intermediateBuffer, outputWeight, outputBias, resultBuffer2, resultBuffer1); #ifdef DEBUG printf("bert/encoder/layer_%d/output/add:\n", layerIdx); dumpMatrix(resultBuffer1); #endif // batchnorm batchnorm(resultBuffer1, gamma2, beta2); #ifdef DEBUG printf("bert/encoder/layer_%d/output/LayerNorm/batchnorm/add_1:\n", layerIdx); dumpMatrix(resultBuffer1); #endif return resultBuffer1; } private: void copyWeights(hpj::Matrix<float> &w, int start_col, int end_col, const float *data) { hpj::Matrix<float> subW(w, 0, w.Rows(), start_col, end_col - start_col); copyWeights(subW, data); } void copyWeights(hpj::Matrix<float> &w, const float *data) { for (int i = 0; i < w.Rows(); ++i) { for (int j = 0; j < w.Cols(); ++j) { w(i, j) = *data++; } } } void copyTransposed(hpj::Matrix<float> &dst, hpj::Matrix<float> &src) { dst.Resize(src.Cols(), src.Rows()); for (int i = 0; i < dst.Rows(); ++i) { for (int j = 0; j < dst.Cols(); ++j) { dst(i, j) = src(j, i); } } } void dumpMatrix(hpj::Matrix<float> &m) { int cols = m.Cols(); for (int i = 0; i < m.Rows(); ++i) { if (m.Cols() < 10) { for (int j = 0; j < m.Cols(); ++j) { std::cout << m(i, j) << " "; } } else { std::cout << m(i, 0) << " " << m(i, 1) << " " << m(i, 2) << " ... " << m(i, cols-3) << " " << m(i, cols-2) << " " << m(i, cols-1); } std::cout << std::endl; } } // C = A * B // bTranspose: B need to be transposed or not void sgemm(hpj::Matrix<float> &A, hpj::Matrix<float> &B, hpj::Matrix<float> &C) { bool bTranspose = (A.Cols() != B.Rows()); int m = inputTokenSize; //As the input token size may be less than max token size, not use A.Rows() any more int k = A.Cols(); int n = (bTranspose ? B.Rows() : B.Cols()); float alpha = 1; float beta = 0; cblas_sgemm(CblasRowMajor, CblasNoTrans, (bTranspose ? CblasTrans : CblasNoTrans), m, n, k, alpha, A.Data(), A.Stride(), B.Data(), B.Stride(), beta, C.Data(), C.Stride()); } // result = x * weight + bias + input void denseWithSum(hpj::Matrix<float> &x, hpj::Matrix<float> &weight, hpj::Vector<float> &bias, hpj::Matrix<float> &input, hpj::Matrix<float> &result) { //assert(input.Rows() == result.Rows()); assert(input.Cols() == result.Cols()); sgemm(x, weight, result); float *pbias = bias.Data(); #pragma omp parallel for for (int i = 0; i < inputTokenSize; ++i) { float *presult = result.Row(i); float *pinput = input.Row(i); #pragma omp simd for (int j = 0; j < result.Cols(); ++j) { presult[j] += pinput[j] + pbias[j]; } } } void batchnorm(hpj::Matrix<float> &x, hpj::Vector<float> &gamma, hpj::Vector<float> &beta) { assert(x.Cols() == hiddenSize); float *pgamma = gamma.Data(); float *pbeta = beta.Data(); #pragma omp parallel for for (int i = 0; i < inputTokenSize; ++i) { float sum = 0; float *px = x.Row(i); #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { sum += px[j]; } float mean = sum / hiddenSize; sum = 0; #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { float delta = (px[j] - mean); sum += delta * delta; } float tmp = sum / hiddenSize + 9.999999960041972e-13; float rvariance = 1.0f / sqrt(tmp); #pragma omp simd for (int j = 0; j < x.Cols(); ++j) { px[j] = (px[j] - mean) * rvariance * pgamma[j] + pbeta[j]; } } } void intermediate(hpj::Matrix<float> &input, hpj::Matrix<float> &output) { sgemm(input, intermediateWeight, output); float *pbias = intermediateBias.Data(); const float factor = sqrt(0.5f); const float scale = 0.5f / factor; #ifdef __INTEL_COMPILER #pragma omp parallel for for (int i = 0; i < inputTokenSize; ++i) { float *pout = output.Row(i); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { float with_bias = pout[j] + pbias[j]; pout[j] = with_bias * 0.5f * (erf(with_bias * factor) + 1); } } #else #pragma omp parallel for for (int i = 0; i < inputTokenSize; ++i) { int tid = omp_get_thread_num(); float *pout = output.Row(i); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { pout[j] = (pout[j] + pbias[j]) * factor; } vsErf(output.Cols(), pout, erf_buffer[tid]); #pragma omp simd for (int j = 0; j < output.Cols(); ++j) { pout[j] = pout[j] * scale * (erf_buffer[tid][j] + 1); } } #endif } // ONLY for dimension 768 // The first BatchMatMul inside self attention void batchMatMul(hpj::Matrix<float> &A, hpj::Matrix<float> &B, float *c_array[12]){ #define GRP_COUNT 1 MKL_INT m[GRP_COUNT] = {inputTokenSize}; MKL_INT k[GRP_COUNT] = {64}; MKL_INT n[GRP_COUNT] = {inputTokenSize}; MKL_INT lda[GRP_COUNT] = {A.Stride()}; MKL_INT ldb[GRP_COUNT] = {B.Stride()}; MKL_INT ldc[GRP_COUNT] = {inputTokenSize}; CBLAS_TRANSPOSE transA[GRP_COUNT] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[GRP_COUNT] = { CblasTrans }; float alpha[GRP_COUNT] = {1.0}; float beta[GRP_COUNT] = {0.0}; const MKL_INT size_per_grp[GRP_COUNT] = {12}; // Total number of multiplications: 12 const float *a_array[12], *b_array[12]; for (int i = 0; i < 12; ++i) { a_array[i] = A.Data() + i * 64; b_array[i] = B.Data() + i * 64; } // Call cblas_sgemm_batch cblas_sgemm_batch ( CblasRowMajor, transA, transB, m, n, k, alpha, a_array, lda, b_array, ldb, beta, c_array, ldc, GRP_COUNT, size_per_grp); } // ONLY for dimension 768 // The second BatchMatMul inside self attention void batchMatMul(float *a_array[12], hpj::Matrix<float> &B, hpj::Matrix<float> &C) { #define GRP_COUNT 1 MKL_INT m[GRP_COUNT] = {inputTokenSize}; MKL_INT k[GRP_COUNT] = {inputTokenSize}; MKL_INT n[GRP_COUNT] = {64}; MKL_INT lda[GRP_COUNT] = {inputTokenSize}; MKL_INT ldb[GRP_COUNT] = {B.Stride()}; MKL_INT ldc[GRP_COUNT] = {C.Stride()}; CBLAS_TRANSPOSE transA[GRP_COUNT] = { CblasNoTrans }; CBLAS_TRANSPOSE transB[GRP_COUNT] = { CblasNoTrans }; float alpha[GRP_COUNT] = {1.0}; float beta[GRP_COUNT] = {0.0}; const MKL_INT size_per_grp[GRP_COUNT] = {12}; // Total number of multiplications: 12 float *b_array[12], *c_array[12]; for (int i = 0; i < 12; ++i) { b_array[i] = B.Data() + i * 64; c_array[i] = C.Data() + i * 64; } // Call cblas_sgemm_batch cblas_sgemm_batch ( CblasRowMajor, transA, transB, m, n, k, alpha, (const float **)a_array, lda, (const float **)b_array, ldb, beta, c_array, ldc, GRP_COUNT, size_per_grp); } // Add bias to matrix void biasAdd(hpj::Matrix<float> &m, hpj::Vector<float> &bias) { float *pbias = bias.Data(); #pragma omp parallel for for (int i = 0; i < inputTokenSize; ++i) { float *p = m.Row(i); #pragma omp simd for (int j = 0; j < m.Cols(); ++j) { p[j] += pbias[j]; } } } // input and output are both in qk_result void computeSoftmax(int actualTokens) { for (int i = 0; i < actualTokens; ++i) { magic_value[i] = 0; } for (int i = actualTokens; i < inputTokenSize; ++i) { magic_value[i] = -10000; } #pragma omp parallel for for (int i = 0; i < 12; ++i) { float *pbuffer = exp_buffer[i]; for (int row = 0; row < inputTokenSize; ++row) { float sum = 0; // max_val is used to avoid exp(x) = inf float max_val = std::numeric_limits<float>::min(); #pragma omp simd for (int j = 0; j < actualTokens; ++j) { if (qk_result[i][row*inputTokenSize+j] > max_val) { max_val = qk_result[i][row*inputTokenSize+j]; } } max_val *= 0.125f; #ifdef __INTEL_COMPILER #pragma omp simd for (int j = 0; j < inputTokenSize; ++j) { pbuffer[j] = exp(qk_result[i][row*inputTokenSize+j] * 0.125f + magic_value[j] - max_val); sum += pbuffer[j]; } #else #pragma omp simd for (int j = 0; j < inputTokenSize; ++j) { pbuffer[j] = qk_result[i][row*inputTokenSize+j] * 0.125f + magic_value[j] - max_val; } vsExp(inputTokenSize, pbuffer, pbuffer); for (int j = 0; j < inputTokenSize; ++j) { sum += pbuffer[j]; } #endif float r_sum = 1.0f / sum; #pragma omp simd for (int j = 0; j < inputTokenSize; ++j) { qk_result[i][row*inputTokenSize+j] = pbuffer[j] * r_sum; } } } } private: // For debug usage int layerIdx; int maxTokenSize; // For some model, the len(input_ids) may be less than maxTokenSize int inputTokenSize; int hiddenSize; int intermediateSize; // Store the result of input*qkvWeight hpj::Matrix<float> qkvMatMul; // Buffer like the dimesion of 128x768 hpj::Matrix<float> resultBuffer1, resultBuffer2; // Buffer to store the result of intermediate hpj::Matrix<float> intermediateBuffer; // Store the BatchMatMul result of query and key float *qk_result[12]; // Store the result of exp for each line float *exp_buffer[12]; // Magic value: 0 or -10000 float *magic_value; int num_threads; #ifndef __INTEL_COMPILER float **erf_buffer; #endif // Merged query, key, value weighs hpj::Matrix<float> qkvWeight; // Merged query, key, value bias hpj::Vector<float> qkvBias; hpj::Matrix<float> attentionOutputWeight; hpj::Vector<float> attentionOutputBias; // batchnorm param hpj::Vector<float> gamma1, beta1; hpj::Vector<float> gamma2, beta2; hpj::Matrix<float> intermediateWeight; hpj::Vector<float> intermediateBias; hpj::Matrix<float> outputWeight; hpj::Vector<float> outputBias; }; #endif
nested-2.c
#include <omp.h> #include <stdlib.h> int main (void) { int i = -1, j = -1; omp_set_nested (0); omp_set_dynamic (0); #pragma omp parallel num_threads (4) { #pragma omp single { i = omp_get_thread_num () + omp_get_num_threads () * 256; #pragma omp parallel num_threads (2) { #pragma omp single { j = omp_get_thread_num () + omp_get_num_threads () * 256; } } } } if (i < 4 * 256 || i >= 4 * 256 + 4) abort (); if (j != 256 + 0) abort (); return 0; }
polysa_t2s.c
#include <limits.h> #include <stdio.h> #include <string.h> #include <isl/aff.h> #include <isl/ctx.h> #include <isl/flow.h> #include <isl/map.h> #include <isl/vec.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <isl/constraint.h> #include <isl/id_to_id.h> #include <pet.h> #include <pet/expr.h> #include "ppcg.h" #include "ppcg_options.h" #include "print.h" #include "schedule.h" #include "util.h" #include "polysa_t2s.h" struct t2s_stmt { char *content; }; static struct t2s_array_ref_group *t2s_array_ref_group_free( struct t2s_array_ref_group *group ) { if (!group) return NULL; isl_map_free(group->access); if (group->n_ref > 1) free(group->refs); free(group); return NULL; } static struct t2s_group_data *t2s_group_data_free(struct t2s_group_data *d) { if (!d) return NULL; isl_union_map_free(d->full_sched); free(d); return NULL; } struct polysa_stmt { struct ppcg_stmt *stmt; /* T2S */ struct t2s_stmt *t_stmt; }; /* Representation of a statement inside a generated AST. * * "stmt" refers to the original statement. * "ref2expr" maps the reference identifier of each access in * the statement to an AST expression that should be printed * at the place of the access. */ struct ppcg_stmt { struct pet_stmt *stmt; isl_id_to_ast_expr *ref2expr; }; static void ppcg_stmt_free(void *user) { struct ppcg_stmt *stmt = user; if (!stmt) return; isl_id_to_ast_expr_free(stmt->ref2expr); free(stmt); } static void t2s_stmt_free(void *user) { struct t2s_stmt *stmt = user; if (!stmt) return; free(stmt); } static void polysa_stmt_free(void *user) { struct polysa_stmt *p_stmt = user; if (!p_stmt) return; ppcg_stmt_free(p_stmt->stmt); t2s_stmt_free(p_stmt->t_stmt); free(p_stmt); } /* Mark if the scheudule at each depth is a sequential node or not. */ static isl_bool update_seq_band(__isl_keep isl_schedule_node *node, void *user) { enum isl_schedule_node_type node_type = isl_schedule_node_get_type(node); enum isl_schedule_node_type *type_depth = user; int total_band_depth = isl_schedule_node_get_schedule_depth(node); int total_seq_depth = 0; isl_schedule_node *node_tmp = isl_schedule_node_copy(node); while (isl_schedule_node_has_parent(node_tmp)) { node_tmp = isl_schedule_node_parent(node_tmp); if (isl_schedule_node_get_type(node_tmp) == isl_schedule_node_sequence) total_seq_depth += 1; } isl_schedule_node_free(node_tmp); int cur_depth = total_band_depth + total_seq_depth; if (node_type == isl_schedule_node_band) { for (int i = 0; i < isl_schedule_node_band_n_member(node); i++) { type_depth[cur_depth + i] = node_type; } } else if (node_type == isl_schedule_node_sequence) { type_depth[cur_depth + 0] = node_type; } return isl_bool_true; } /* Peel off the iterators for scalar dimensions in a vector. */ static __isl_give isl_vec *t2s_peel_off_scalar_dims_vec(__isl_take isl_vec *vec, __isl_keep isl_schedule *schedule) { isl_schedule_node *root = isl_schedule_get_root(schedule); isl_union_map *full_sched = isl_schedule_node_get_subtree_schedule_union_map(root); isl_set *sched_range = isl_set_from_union_set(isl_union_map_range(full_sched)); int sched_depth = isl_set_dim(sched_range, isl_dim_set); isl_set_free(sched_range); isl_schedule_node_free(root); isl_ctx *ctx = isl_vec_get_ctx(vec); enum isl_schedule_node_type *type_depth = isl_calloc_array(isl_schedule_get_ctx(schedule), enum isl_schedule_node_type, sched_depth); for (int i = 0; i < sched_depth; i++) { type_depth[i] = -1; } isl_schedule_foreach_schedule_node_top_down( schedule, &update_seq_band, type_depth); isl_vec *new_vec = isl_vec_alloc(isl_vec_get_ctx(vec), 0); for (int i = 0; i < sched_depth; i++) { if (type_depth[i] != isl_schedule_node_sequence) { isl_vec *vec_i = isl_vec_alloc(ctx, 1); vec_i = isl_vec_set_element_val(vec_i, 0, isl_vec_get_element_val(vec, i)); new_vec = isl_vec_concat(new_vec, vec_i); } } free(type_depth); isl_vec_free(vec); return new_vec; } /* Peel off the iterators for scalar dimenisions in the iteration domain "set". */ static __isl_give isl_set *t2s_peel_off_scalar_dims(__isl_take isl_set *set, __isl_keep isl_schedule *schedule) { isl_schedule_node *root = isl_schedule_get_root(schedule); isl_union_map *full_sched = isl_schedule_node_get_subtree_schedule_union_map(root); isl_set *sched_range = isl_set_from_union_set(isl_union_map_range(full_sched)); int sched_depth = isl_set_dim(sched_range, isl_dim_set); isl_set_free(sched_range); isl_schedule_node_free(root); enum isl_schedule_node_type *type_depth = isl_calloc_array(isl_schedule_get_ctx(schedule), enum isl_schedule_node_type, sched_depth); for (int i = 0; i < sched_depth; i++) { type_depth[i] = -1; } isl_schedule_foreach_schedule_node_top_down( schedule, &update_seq_band, type_depth); int proj_dim = 0; for (int i = 0; i < sched_depth; i++) { if (type_depth[i] == isl_schedule_node_sequence) { set = isl_set_project_out(set, isl_dim_set, i - proj_dim, 1); proj_dim++; } } free(type_depth); return set; } /* Derive the output file name from the input file name. * 'input' is the entire path of the input file. The output * is the file name plus the additional extension. * * We will basically replace everything after the last point * with '.polysa.c'. This means file.c becomes file.polysa.c */ static FILE *get_output_file(const char *input, const char *output) { char name[PATH_MAX]; const char *ext; const char ppcg_marker[] = ".polysa"; int len; FILE *file; len = ppcg_extract_base_name(name, input); strcpy(name + len, ppcg_marker); ext = strrchr(input, '.'); strcpy(name + len + sizeof(ppcg_marker) - 1, ext ? ext : ".c"); if (!output) output = name; file = fopen(output, "w"); if (!file) { fprintf(stderr, "Unable to open '%s' for writing\n", output); return NULL; } return file; } /* Data used to annotate for nodes in the ast. */ struct ast_node_userinfo { /* The for node is an openmp parallel for node. */ int is_openmp; }; /* Information used while building the ast. */ struct ast_build_userinfo { /* The current ppcg scop. */ struct ppcg_scop *scop; /* Are we currently in a parallel for loop? */ int in_parallel_for; }; /* Check if the current scheduling dimension is parallel. * * We check for parallelism by verifying that the loop does not carry any * dependences. * If the live_range_reordering option is set, then this currently * includes the order dependences. In principle, non-zero order dependences * could be allowed, but this would require privatization and/or expansion. * * Parallelism test: if the distance is zero in all outer dimensions, then it * has to be zero in the current dimension as well. * Implementation: first, translate dependences into time space, then force * outer dimensions to be equal. If the distance is zero in the current * dimension, then the loop is parallel. * The distance is zero in the current dimension if it is a subset of a map * with equal values for the current dimension. */ static int ast_schedule_dim_is_parallel(__isl_keep isl_ast_build *build, struct ppcg_scop *scop) { isl_union_map *schedule, *deps; isl_map *schedule_deps, *test; isl_space *schedule_space; unsigned i, dimension, is_parallel; schedule = isl_ast_build_get_schedule(build); schedule_space = isl_ast_build_get_schedule_space(build); dimension = isl_space_dim(schedule_space, isl_dim_out) - 1; deps = isl_union_map_copy(scop->dep_flow); deps = isl_union_map_union(deps, isl_union_map_copy(scop->dep_false)); if (scop->options->live_range_reordering) { isl_union_map *order = isl_union_map_copy(scop->dep_order); deps = isl_union_map_union(deps, order); } deps = isl_union_map_apply_range(deps, isl_union_map_copy(schedule)); deps = isl_union_map_apply_domain(deps, schedule); if (isl_union_map_is_empty(deps)) { isl_union_map_free(deps); isl_space_free(schedule_space); return 1; } schedule_deps = isl_map_from_union_map(deps); for (i = 0; i < dimension; i++) schedule_deps = isl_map_equate(schedule_deps, isl_dim_out, i, isl_dim_in, i); test = isl_map_universe(isl_map_get_space(schedule_deps)); test = isl_map_equate(test, isl_dim_out, dimension, isl_dim_in, dimension); is_parallel = isl_map_is_subset(schedule_deps, test); isl_space_free(schedule_space); isl_map_free(test); isl_map_free(schedule_deps); return is_parallel; } /* Mark a for node openmp parallel, if it is the outermost parallel for node. */ static void mark_openmp_parallel(__isl_keep isl_ast_build *build, struct ast_build_userinfo *build_info, struct ast_node_userinfo *node_info) { if (build_info->in_parallel_for) return; if (ast_schedule_dim_is_parallel(build, build_info->scop)) { build_info->in_parallel_for = 1; node_info->is_openmp = 1; } } /* Allocate an ast_node_info structure and initialize it with default values. */ static struct ast_node_userinfo *allocate_ast_node_userinfo() { struct ast_node_userinfo *node_info; node_info = (struct ast_node_userinfo *) malloc(sizeof(struct ast_node_userinfo)); node_info->is_openmp = 0; return node_info; } /* Free an ast_node_info structure. */ static void free_ast_node_userinfo(void *ptr) { struct ast_node_userinfo *info; info = (struct ast_node_userinfo *) ptr; free(info); } /* This method is executed before the construction of a for node. It creates * an isl_id that is used to annotate the subsequently generated ast for nodes. * * In this function we also run the following analyses: * * - Detection of openmp parallel loops */ static __isl_give isl_id *ast_build_before_for( __isl_keep isl_ast_build *build, void *user) { isl_id *id; struct ast_build_userinfo *build_info; struct ast_node_userinfo *node_info; build_info = (struct ast_build_userinfo *) user; node_info = allocate_ast_node_userinfo(); id = isl_id_alloc(isl_ast_build_get_ctx(build), "", node_info); id = isl_id_set_free_user(id, free_ast_node_userinfo); mark_openmp_parallel(build, build_info, node_info); return id; } /* This method is executed after the construction of a for node. * * It performs the following actions: * * - Reset the 'in_parallel_for' flag, as soon as we leave a for node, * that is marked as openmp parallel. * */ static __isl_give isl_ast_node *ast_build_after_for( __isl_take isl_ast_node *node, __isl_keep isl_ast_build *build, void *user) { isl_id *id; struct ast_build_userinfo *build_info; struct ast_node_userinfo *info; id = isl_ast_node_get_annotation(node); info = isl_id_get_user(id); if (info && info->is_openmp) { build_info = (struct ast_build_userinfo *) user; build_info->in_parallel_for = 0; } isl_id_free(id); return node; } /* Find the element in scop->stmts that has the given "id". */ static struct pet_stmt *find_stmt(struct ppcg_scop *scop, __isl_keep isl_id *id) { int i; for (i = 0; i < scop->pet->n_stmt; ++i) { struct pet_stmt *stmt = scop->pet->stmts[i]; isl_id *id_i; id_i = isl_set_get_tuple_id(stmt->domain); isl_id_free(id_i); if (id_i == id) return stmt; } isl_die(isl_id_get_ctx(id), isl_error_internal, "statement not found", return NULL); } /* Print a user statement in the generated AST. * The ppcg_stmt has been attached to the node in at_each_domain. */ static __isl_give isl_printer *print_user(__isl_take isl_printer *p, __isl_take isl_ast_print_options *print_options, __isl_keep isl_ast_node *node, void *user) { struct ppcg_stmt *stmt; isl_id *id; id = isl_ast_node_get_annotation(node); stmt = isl_id_get_user(id); isl_id_free(id); p = pet_stmt_print_body(stmt->stmt, p, stmt->ref2expr); isl_ast_print_options_free(print_options); return p; } /* Print a for loop node as an openmp parallel loop. * * To print an openmp parallel loop we print a normal for loop, but add * "#pragma openmp parallel for" in front. * * Variables that are declared within the body of this for loop are * automatically openmp 'private'. Iterators declared outside of the * for loop are automatically openmp 'shared'. As ppcg declares all iterators * at the position where they are assigned, there is no need to explicitly mark * variables. Their automatically assigned type is already correct. * * This function only generates valid OpenMP code, if the ast was generated * with the 'atomic-bounds' option enabled. * */ static __isl_give isl_printer *print_for_with_openmp( __isl_keep isl_ast_node *node, __isl_take isl_printer *p, __isl_take isl_ast_print_options *print_options) { p = isl_printer_start_line(p); p = isl_printer_print_str(p, "#pragma omp parallel for"); p = isl_printer_end_line(p); p = isl_ast_node_for_print(node, p, print_options); return p; } /* Print a for node. * * Depending on how the node is annotated, we either print a normal * for node or an openmp parallel for node. */ static __isl_give isl_printer *print_for(__isl_take isl_printer *p, __isl_take isl_ast_print_options *print_options, __isl_keep isl_ast_node *node, void *user) { isl_id *id; int openmp; openmp = 0; id = isl_ast_node_get_annotation(node); if (id) { struct ast_node_userinfo *info; info = (struct ast_node_userinfo *) isl_id_get_user(id); if (info && info->is_openmp) openmp = 1; } if (openmp) p = print_for_with_openmp(node, p, print_options); else p = isl_ast_node_for_print(node, p, print_options); isl_id_free(id); return p; } /* Index transformation callback for pet_stmt_build_ast_exprs. * * "index" expresses the array indices in terms of statement iterators * "iterator_map" expresses the statement iterators in terms of * AST loop iterators. * * The result expresses the array indices in terms of * AST loop iterators. */ static __isl_give isl_multi_pw_aff *pullback_index( __isl_take isl_multi_pw_aff *index, __isl_keep isl_id *id, void *user) { isl_pw_multi_aff *iterator_map = user; iterator_map = isl_pw_multi_aff_copy(iterator_map); return isl_multi_pw_aff_pullback_pw_multi_aff(index, iterator_map); } /* Transform the accesses in the statement associated to the domain * called by "node" to refer to the AST loop iterators, construct * corresponding AST expressions using "build", * collect them in a ppcg_stmt and annotate the node with the ppcg_stmt. */ static __isl_give isl_ast_node *at_each_domain(__isl_take isl_ast_node *node, __isl_keep isl_ast_build *build, void *user) { struct ppcg_scop *scop = user; isl_ast_expr *expr, *arg; isl_ctx *ctx; isl_id *id; isl_map *map; isl_pw_multi_aff *iterator_map; struct ppcg_stmt *stmt; ctx = isl_ast_node_get_ctx(node); stmt = isl_calloc_type(ctx, struct ppcg_stmt); if (!stmt) goto error; expr = isl_ast_node_user_get_expr(node); arg = isl_ast_expr_get_op_arg(expr, 0); isl_ast_expr_free(expr); id = isl_ast_expr_get_id(arg); isl_ast_expr_free(arg); stmt->stmt = find_stmt(scop, id); isl_id_free(id); if (!stmt->stmt) goto error; map = isl_map_from_union_map(isl_ast_build_get_schedule(build)); map = isl_map_reverse(map); iterator_map = isl_pw_multi_aff_from_map(map); stmt->ref2expr = pet_stmt_build_ast_exprs(stmt->stmt, build, &pullback_index, iterator_map, NULL, NULL); isl_pw_multi_aff_free(iterator_map); id = isl_id_alloc(isl_ast_node_get_ctx(node), NULL, stmt); id = isl_id_set_free_user(id, &ppcg_stmt_free); return isl_ast_node_set_annotation(node, id); error: ppcg_stmt_free(stmt); return isl_ast_node_free(node); } /* Set *depth (initialized to 0 by the caller) to the maximum * of the schedule depths of the leaf nodes for which this function is called. */ static isl_bool update_depth(__isl_keep isl_schedule_node *node, void *user) { int *depth = user; int node_depth; if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) return isl_bool_true; node_depth = isl_schedule_node_get_schedule_depth(node); if (node_depth > *depth) *depth = node_depth; return isl_bool_false; } /* This function is called for each node in a CPU AST. * In case of a user node, print the macro definitions required * for printing the AST expressions in the annotation, if any. * For other nodes, return true such that descendants are also * visited. * * In particular, print the macro definitions needed for the substitutions * of the original user statements. */ static isl_bool at_node(__isl_keep isl_ast_node *node, void *user) { struct ppcg_stmt *stmt; isl_id *id; isl_printer **p = user; if (isl_ast_node_get_type(node) != isl_ast_node_user) return isl_bool_true; id = isl_ast_node_get_annotation(node); stmt = isl_id_get_user(id); isl_id_free(id); if (!stmt) return isl_bool_error; *p = ppcg_print_body_macros(*p, stmt->ref2expr); if (!*p) return isl_bool_error; return isl_bool_false; } /* Print the required macros for the CPU AST "node" to "p", * including those needed for the user statements inside the AST. */ static __isl_give isl_printer *cpu_print_macros(__isl_take isl_printer *p, __isl_keep isl_ast_node *node) { if (isl_ast_node_foreach_descendant_top_down(node, &at_node, &p) < 0) return isl_printer_free(p); p = ppcg_print_macros(p, node); return p; } static isl_bool debug_ast_node(__isl_keep isl_ast_node *node, void *user) { enum isl_ast_node_type type = isl_ast_node_get_type(node); switch (type) { case isl_ast_node_user: printf("user node found.\n"); break; } return isl_bool_true; } /* Code generate the scop 'scop' using "schedule" * and print the corresponding C code to 'p'. */ static __isl_give isl_printer *print_scop(struct ppcg_scop *scop, __isl_take isl_schedule *schedule, __isl_take isl_printer *p, struct ppcg_options *options) { isl_ctx *ctx = isl_printer_get_ctx(p); isl_ast_build *build; isl_ast_print_options *print_options; isl_ast_node *tree; isl_id_list *iterators; struct ast_build_userinfo build_info; int depth; depth = 0; if (isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth, &depth) < 0) goto error; build = isl_ast_build_alloc(ctx); iterators = ppcg_scop_generate_names(scop, depth, "c"); build = isl_ast_build_set_iterators(build, iterators); build = isl_ast_build_set_at_each_domain(build, &at_each_domain, scop); if (options->openmp) { build_info.scop = scop; build_info.in_parallel_for = 0; build = isl_ast_build_set_before_each_for(build, &ast_build_before_for, &build_info); build = isl_ast_build_set_after_each_for(build, &ast_build_after_for, &build_info); } tree = isl_ast_build_node_from_schedule(build, schedule); isl_ast_build_free(build); print_options = isl_ast_print_options_alloc(ctx); print_options = isl_ast_print_options_set_print_user(print_options, &print_user, NULL); print_options = isl_ast_print_options_set_print_for(print_options, &print_for, NULL); p = cpu_print_macros(p, tree); p = isl_ast_node_print(tree, p, print_options); isl_ast_node_free(tree); return p; error: isl_schedule_free(schedule); isl_printer_free(p); return NULL; } /* Tile the band node "node" with tile sizes "sizes" and * mark all members of the resulting tile node as "atomic". */ static __isl_give isl_schedule_node *tile(__isl_take isl_schedule_node *node, __isl_take isl_multi_val *sizes) { node = isl_schedule_node_band_tile(node, sizes); node = ppcg_set_schedule_node_type(node, isl_ast_loop_atomic); return node; } /* Tile "node", if it is a band node with at least 2 members. * The tile sizes are set from the "tile_size" option. */ static __isl_give isl_schedule_node *tile_band( __isl_take isl_schedule_node *node, void *user) { struct ppcg_scop *scop = user; int n; isl_space *space; isl_multi_val *sizes; if (isl_schedule_node_get_type(node) != isl_schedule_node_band) return node; n = isl_schedule_node_band_n_member(node); if (n <= 1) return node; space = isl_schedule_node_band_get_space(node); sizes = ppcg_multi_val_from_int(space, scop->options->tile_size); return tile(node, sizes); } /* Construct schedule constraints from the dependences in ps * for the purpose of computing a schedule for a CPU. * * The proximity constraints are set to the flow dependences. * * If live-range reordering is allowed then the conditional validity * constraints are set to the order dependences with the flow dependences * as condition. That is, a live-range (flow dependence) will be either * local to an iteration of a band or all adjacent order dependences * will be respected by the band. * The validity constraints are set to the union of the flow dependences * and the forced dependences, while the coincidence constraints * are set to the union of the flow dependences, the forced dependences and * the order dependences. * * If live-range reordering is not allowed, then both the validity * and the coincidence constraints are set to the union of the flow * dependences and the false dependences. * * Note that the coincidence constraints are only set when the "openmp" * options is set. Even though the way openmp pragmas are introduced * does not rely on the coincident property of the schedule band members, * the coincidence constraints do affect the way the schedule is constructed, * such that more schedule dimensions should be detected as parallel * by ast_schedule_dim_is_parallel. * Since the order dependences are also taken into account by * ast_schedule_dim_is_parallel, they are also added to * the coincidence constraints. If the openmp handling learns * how to privatize some memory, then the corresponding order * dependences can be removed from the coincidence constraints. */ static __isl_give isl_schedule_constraints *construct_cpu_schedule_constraints( struct ppcg_scop *ps) { isl_schedule_constraints *sc; isl_union_map *validity, *coincidence; sc = isl_schedule_constraints_on_domain(isl_union_set_copy(ps->domain)); if (ps->options->live_range_reordering) { sc = isl_schedule_constraints_set_conditional_validity(sc, isl_union_map_copy(ps->tagged_dep_flow), isl_union_map_copy(ps->tagged_dep_order)); validity = isl_union_map_copy(ps->dep_flow); validity = isl_union_map_union(validity, isl_union_map_copy(ps->dep_forced)); // if (ps->options->openmp) { coincidence = isl_union_map_copy(validity); coincidence = isl_union_map_union(coincidence, isl_union_map_copy(ps->dep_order)); // } /* Add the RAR dependences into the validity constraints for * systolic array generation. */ if (ps->options->polysa) { validity = isl_union_map_union(validity, isl_union_map_copy(ps->dep_rar)); } } else { validity = isl_union_map_copy(ps->dep_flow); validity = isl_union_map_union(validity, isl_union_map_copy(ps->dep_false)); // if (ps->options->openmp) coincidence = isl_union_map_copy(validity); /* Add the RAR dependences into the validity constraints for * systolic array generation. */ if (ps->options->polysa) { validity = isl_union_map_union(validity, isl_union_map_copy(ps->dep_rar)); } } // if (ps->options->openmp) sc = isl_schedule_constraints_set_coincidence(sc, coincidence); sc = isl_schedule_constraints_set_validity(sc, validity); sc = isl_schedule_constraints_set_proximity(sc, isl_union_map_copy(ps->dep_flow)); return sc; } /* Compute a schedule for the scop "ps". * * First derive the appropriate schedule constraints from the dependences * in "ps" and then compute a schedule from those schedule constraints, * possibly grouping statement instances based on the input schedule. */ static __isl_give isl_schedule *compute_cpu_schedule(struct ppcg_scop *ps) { isl_schedule_constraints *sc; isl_schedule *schedule; if (!ps) return NULL; sc = construct_cpu_schedule_constraints(ps); schedule = ppcg_compute_schedule(sc, ps->schedule, ps->options); return schedule; } /* Compute a new schedule to the scop "ps" if the reschedule option is set. * Otherwise, return a copy of the original schedule. */ static __isl_give isl_schedule *optionally_compute_schedule(void *user) { struct ppcg_scop *ps = user; if (!ps) return NULL; if (!ps->options->reschedule) return isl_schedule_copy(ps->schedule); return compute_cpu_schedule(ps); } /* Compute a schedule based on the dependences in "ps" and * tile it if requested by the user. */ static __isl_give isl_schedule *get_schedule(struct ppcg_scop *ps, struct ppcg_options *options) { isl_ctx *ctx; isl_schedule *schedule; if (!ps) return NULL; ctx = isl_union_set_get_ctx(ps->domain); schedule = ppcg_get_schedule(ctx, options, &optionally_compute_schedule, ps); if (ps->options->tile) schedule = isl_schedule_map_schedule_node_bottom_up(schedule, &tile_band, ps); return schedule; } /* Generate CPU code for the scop "ps" using "schedule" and * print the corresponding C code to "p", including variable declarations. */ static __isl_give isl_printer *print_cpu_with_schedule( __isl_take isl_printer *p, struct ppcg_scop *ps, __isl_take isl_schedule *schedule, struct ppcg_options *options) { int hidden; isl_set *context; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "/* PPCG generated CPU code */"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); p = ppcg_set_macro_names(p); p = ppcg_print_exposed_declarations(p, ps); hidden = ppcg_scop_any_hidden_declarations(ps); if (hidden) { p = ppcg_start_block(p); p = ppcg_print_hidden_declarations(p, ps); } context = isl_set_copy(ps->context); context = isl_set_from_params(context); schedule = isl_schedule_insert_context(schedule, context); if (options->debug->dump_final_schedule) isl_schedule_dump(schedule); p = print_scop(ps, schedule, p, options); if (hidden) p = ppcg_end_block(p); return p; } //static __isl_give isl_schedule_node *aggregate_stmt_domain(__isl_take isl_schedule_node *node, void *user) //{ // isl_union_set *domain; // isl_union_map *schedule; // isl_set *stmt_domain; // isl_set **anchor_domain = (isl_set **)(user); // // if (!node) // return NULL; // // if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) // return node; // // domain = isl_schedule_node_get_domain(node); // schedule = isl_schedule_node_get_prefix_schedule_union_map(node); // schedule = isl_union_map_intersect_domain(schedule, domain); // stmt_domain = isl_set_from_union_set(isl_union_map_range(schedule)); // if (*anchor_domain == NULL) // *anchor_domain = isl_set_copy(stmt_domain); // else // *anchor_domain = isl_set_union(*anchor_domain, isl_set_copy(stmt_domain)); // // isl_set_free(stmt_domain); // // return node; //} /* Extract the (simplified) iteration domain of each user statement. */ static isl_stat extract_each_stmt_domain(__isl_take isl_set *set, void *user) { struct t2s_data *data = user; isl_union_set *sched_domain = isl_union_set_apply(isl_union_set_from_set(isl_set_copy(set)), isl_union_map_copy(data->sched)); isl_set *stmt_domain_i = isl_set_from_union_set(sched_domain); isl_set *stmt_sim_domain_i = isl_set_gist(isl_set_copy(stmt_domain_i), isl_set_copy(data->anchor_domain)); /* Set the name of space. */ isl_space *space = isl_set_get_space(set); const char *stmt_name = isl_space_get_tuple_name(space, isl_dim_set); stmt_domain_i = isl_set_set_tuple_name(stmt_domain_i, stmt_name); stmt_sim_domain_i = isl_set_set_tuple_name(stmt_sim_domain_i, stmt_name); isl_set_free(set); isl_space_free(space); if (data->stmt_domain == NULL) data->stmt_domain = isl_union_set_from_set(stmt_domain_i); else data->stmt_domain = isl_union_set_union(data->stmt_domain, isl_union_set_from_set(stmt_domain_i)); if (data->stmt_sim_domain == NULL) data->stmt_sim_domain = isl_union_set_from_set(stmt_sim_domain_i); else data->stmt_sim_domain = isl_union_set_union(data->stmt_sim_domain, isl_union_set_from_set(stmt_sim_domain_i)); return isl_stat_ok; } /* Extract the (simplified) iteration domain of all the user statemets. */ static isl_stat extract_stmt_domain(__isl_keep isl_schedule *schedule, struct t2s_data *data) { isl_union_set *domain = isl_schedule_get_domain(schedule); isl_schedule_node *root = isl_schedule_get_root(schedule); isl_union_map *sched = isl_schedule_node_get_subtree_schedule_union_map(root); data->sched = sched; isl_schedule_node_free(root); /* Assign the scheduling space the same name as the statement. */ isl_union_set_foreach_set(domain, &extract_each_stmt_domain, data); isl_union_set_free(domain); data->sched = isl_union_map_free(data->sched); } /* Duplicate the polysa_dep. */ __isl_give struct polysa_dep *polysa_dep_copy(__isl_keep struct polysa_dep *dep) { struct polysa_dep *new_dep = (struct polysa_dep *)malloc(sizeof(struct polysa_dep)); new_dep->src = isl_id_copy(dep->src); new_dep->dest = isl_id_copy(dep->dest); new_dep->disvec = isl_vec_copy(dep->disvec); new_dep->isl_dep = isl_basic_map_copy(dep->isl_dep); new_dep->type = dep->type; new_dep->src_sched_domain = isl_set_copy(dep->src_sched_domain); new_dep->dest_sched_domain = isl_set_copy(dep->dest_sched_domain); return new_dep; } /* This function extracts the raw and rar deps that have the dest access associated * with the current access. */ static int t2s_update_dep(__isl_keep pet_expr *expr, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data = data->stmt_data; isl_id *id; id = isl_id_copy(expr->acc.ref_id); int n; for (n = 0; n < data->ndeps; n++) { struct polysa_dep *dep_i = data->deps[n]; if (dep_i->dest == id && dep_i->type == POLYSA_DEP_RAW) break; } if (n != data->ndeps) { stmt_data->stmt_deps = (struct polysa_dep ***)realloc(stmt_data->stmt_deps, (stmt_data->n_acc_group + 1) * sizeof(struct polysa_dep **)); stmt_data->stmt_deps[stmt_data->n_acc_group] = NULL; stmt_data->n_dep_per_acc_group = (int *)realloc(stmt_data->n_dep_per_acc_group, (stmt_data->n_acc_group + 1) * sizeof(int)); stmt_data->n_dep_per_acc_group[stmt_data->n_acc_group] = 0; for (int i = 0; i < data->ndeps; i++) { struct polysa_dep *dep_i = data->deps[i]; if (dep_i->dest == id && dep_i->type == POLYSA_DEP_RAW) { stmt_data->stmt_deps[stmt_data->n_acc_group] = (struct polysa_dep **)realloc(stmt_data->stmt_deps[stmt_data->n_acc_group], (stmt_data->n_dep_per_acc_group[stmt_data->n_acc_group] + 1) * sizeof(struct polysa_dep *)); stmt_data->stmt_deps[stmt_data->n_acc_group][stmt_data->n_dep_per_acc_group[stmt_data->n_acc_group]] = polysa_dep_copy(dep_i); stmt_data->n_dep_per_acc_group[stmt_data->n_acc_group] += 1; } } stmt_data->n_acc_group += 1; } isl_id_free(id); return 0; } /* Generate the t2s function for each array access. */ static int t2s_update_access(__isl_keep pet_expr *expr, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data = data->stmt_data; isl_id *id; isl_multi_pw_aff *index; isl_space *index_space; isl_id *array_id; isl_ctx *ctx; isl_ast_expr *ast_expr; id = isl_id_copy(expr->acc.ref_id); index = isl_multi_pw_aff_copy(expr->acc.index); ctx = isl_id_get_ctx(id); isl_multi_pw_aff_free(index); /* If the access is associated with RAR, then generate access as * A(c0, c1, c2). * If the access is associated with RAW, then generate access as * A(c0, c1 - 1, c2). * Otherwise, generate A(c0, c1, c2). */ isl_id *func = isl_id_to_id_get(data->ref2func, isl_id_copy(id)); isl_ast_expr *func_expr = isl_ast_expr_from_id(func); isl_ast_expr_list *args = isl_ast_expr_list_alloc(ctx, 0); int i; for (i = 0; i < stmt_data->n_acc_group; i++) { struct polysa_dep *dep_i = stmt_data->dep_stmt_pair[i]; if (dep_i->dest == id && dep_i->type == POLYSA_DEP_RAW) { for (int j = 0; j < data->iter_num; j++) { char iter_name[100]; isl_val *ele = isl_vec_get_element_val(dep_i->disvec, j); if (isl_val_is_zero(ele)) { sprintf(iter_name, "c%d", j); } else { sprintf(iter_name, "c%d - %ld", j, isl_val_get_num_si(ele)); } isl_id *arg = isl_id_alloc(ctx, iter_name, NULL); isl_ast_expr *arg_expr = isl_ast_expr_from_id(arg); args = isl_ast_expr_list_add(args, arg_expr); isl_val_free(ele); } /* Update the func_expr as the src func_expr. */ func = isl_id_to_id_get(data->ref2func, isl_id_copy(dep_i->src)); isl_ast_expr_free(func_expr); func_expr = isl_ast_expr_from_id(func); ast_expr = isl_ast_expr_access(func_expr, args); break; } } if (i == stmt_data->n_acc_group) { for (int j = 0; j < data->iter_num; j++) { char iter_name[100]; sprintf(iter_name, "c%d", j); isl_id *arg = isl_id_alloc(ctx, iter_name, NULL); isl_ast_expr *arg_expr = isl_ast_expr_from_id(arg); args = isl_ast_expr_list_add(args, arg_expr); } ast_expr = isl_ast_expr_access(func_expr, args); } stmt_data->stmts[stmt_data->stmt_num - 1]->ref2expr = isl_id_to_ast_expr_set(stmt_data->stmts[stmt_data->stmt_num - 1]->ref2expr, id, ast_expr); return 0; } /* Free up the dependence. */ void *polysa_dep_free(__isl_take struct polysa_dep *dep) { if (!dep) return NULL; isl_id_free(dep->src); isl_id_free(dep->dest); isl_vec_free(dep->disvec); isl_set_free(dep->src_sched_domain); isl_set_free(dep->dest_sched_domain); isl_basic_map_free(dep->isl_dep); free(dep); return NULL; } /* Generate a T2S statement for each unique dependence pair. */ isl_bool gen_t2s_stmt(__isl_take struct polysa_dep **dep_stmt_pair, struct ppcg_stmt *stmt, struct t2s_data *data) { struct t2s_stmt_data *stmt_data = data->stmt_data; isl_set *union_domain = isl_set_copy(data->stmt_data->stmt_anchor_domain); if (data->stmt_data->n_acc_group > 0) { for (int i = 0; i < data->stmt_data->n_acc_group; i++) { struct polysa_dep *dep_i = dep_stmt_pair[i]; isl_set *dest_sched_domain = isl_set_copy(dep_i->dest_sched_domain); dest_sched_domain = isl_set_set_tuple_id(dest_sched_domain, isl_set_get_tuple_id(union_domain)); union_domain = isl_set_intersect(union_domain, dest_sched_domain); } if (isl_set_is_empty(union_domain)) { free(dep_stmt_pair); isl_set_free(union_domain); return isl_bool_false; } } /* Simplify the domain. */ isl_set *anchor_domain = isl_set_copy(data->anchor_domain); isl_space *space = isl_set_get_space(union_domain); anchor_domain = isl_set_set_tuple_name(anchor_domain, isl_space_get_tuple_name(space, isl_dim_set)); union_domain = isl_set_gist(union_domain, anchor_domain); isl_space_free(space); /* Peel off the scalar dimensions. */ union_domain = t2s_peel_off_scalar_dims(union_domain, data->schedule); data->stmt_data->stmt_num += 1; data->stmt_data->stmts = (struct ppcg_stmt **)realloc(data->stmt_data->stmts, data->stmt_data->stmt_num * sizeof(struct ppcg_stmt *)); data->stmt_data->stmts[data->stmt_data->stmt_num - 1] = (struct ppcg_stmt *)malloc(sizeof(struct ppcg_stmt)); data->stmt_data->stmt_domain = (isl_set **)realloc(data->stmt_data->stmt_domain, data->stmt_data->stmt_num * sizeof(isl_set *)); data->stmt_data->stmt_domain[data->stmt_data->stmt_num - 1] = union_domain; stmt_data->stmts[stmt_data->stmt_num - 1]->stmt = stmt->stmt; stmt_data->stmts[stmt_data->stmt_num - 1]->ref2expr = isl_id_to_ast_expr_alloc(data->ctx, 0); /* Produce the ref2expr for each access. */ stmt_data->dep_stmt_pair = dep_stmt_pair; pet_tree_foreach_access_expr(stmt->stmt->body, &t2s_update_access, data); free(dep_stmt_pair); stmt_data->dep_stmt_pair = NULL; return isl_bool_true; } /* This function builds the ref2expr for each array reference in the user statement. * The LHS access A[][] is replaced by A(c0, c1, c2). * The RHS acesss B[][] is replaced by the flow dep B(c0 - 1, c1, c2). * If the RHS access is associated with multiple flow deps, we will need to the split the statement into multiple T2S statement. * At present, we don't support stmts with more than one RHS access that are associated with flow deps. * * First determine how many unique ref2expr pairs are to be generated. * Then build the ref2expr for each pair. */ static isl_stat extract_t2s_stmt_access(__isl_take struct ppcg_stmt *stmt, struct t2s_data *data) { struct t2s_stmt_data *stmt_data = data->stmt_data; /* Determine all the unique ref2expr pairs to be generated. */ pet_tree_foreach_access_expr(stmt->stmt->body, &t2s_update_dep, data); int stmt_num = 1; for (int i = 0; i < stmt_data->n_acc_group; i++) { stmt_num *= stmt_data->n_dep_per_acc_group[i]; } struct polysa_dep ***dep_stmt_pairs = NULL; dep_stmt_pairs = (struct polysa_dep ***)malloc(stmt_num * sizeof(struct polysa_dep **)); for (int i = 0; i < stmt_num; i++) { dep_stmt_pairs[i] = (struct polysa_dep **)malloc(stmt_data->n_acc_group * sizeof(struct polysa_dep *)); } int prev_repeat = 1; int post_repeat = stmt_num; int acc_group_i = 0; while(acc_group_i < stmt_data->n_acc_group) { int cur_n_dep_acc_group = stmt_data->n_dep_per_acc_group[acc_group_i]; post_repeat /= cur_n_dep_acc_group; int id = 0; for (int i = 0; i < prev_repeat; i++) for (int j = 0; j < cur_n_dep_acc_group; j++) for (int k = 0; k < post_repeat; k++) { dep_stmt_pairs[id][acc_group_i] = stmt_data->stmt_deps[acc_group_i][j]; id++; } acc_group_i++; prev_repeat *= cur_n_dep_acc_group; } /* Gnerate a seperate ppcg_stmt for each dep pair. */ stmt_data->stmt_num = 0; for (int i = 0; i < stmt_num; i++) { isl_bool success = gen_t2s_stmt(dep_stmt_pairs[i], stmt, data); if (!success) { for (int j = i; j < stmt_num - 1; j++) { dep_stmt_pairs[j] = dep_stmt_pairs[j + 1]; } stmt_num -= 1; i--; } } ppcg_stmt_free(stmt); free(dep_stmt_pairs); return isl_stat_ok; } //static char *concat(const char *s1, const char *s2) //{ // char *result = malloc(strlen(s1) + strlen(s2) + 1); // strcpy(result, s1); // strcat(result, s2); // return result; //} /* Print an "set" in T2S format. */ static char *isl_set_to_t2s_format(__isl_keep isl_set *set) { char *t2s_cst = NULL; int n_bset = isl_set_n_basic_set(set); int bset_id = 0; int multi_bset = n_bset > 1; isl_basic_set_list *bset_list = isl_set_get_basic_set_list(set); isl_printer *p = isl_printer_to_str(isl_set_get_ctx(set)); while (bset_id < n_bset) { if (bset_id > 0) { p = isl_printer_print_str(p, " || "); } if (multi_bset) { p = isl_printer_print_str(p, "("); } /* Print the content of each basic map. */ isl_basic_set *bset = isl_basic_set_list_get_basic_set(bset_list, bset_id); isl_constraint_list *cst_list = isl_basic_set_get_constraint_list(bset); int cst_id = 0; int n_cst = isl_basic_set_n_constraint(bset); int multi_cst = n_cst > 1; while (cst_id < n_cst) { if (cst_id > 0) { p = isl_printer_print_str(p, " && "); } if (multi_cst) { p = isl_printer_print_str(p, "("); } isl_constraint *cst_i = isl_constraint_list_get_constraint(cst_list, cst_id); /* TODO: consider isl_dim_div later. */ int is_first = 1; for (int i = 0; i < isl_constraint_dim(cst_i, isl_dim_set); i++) { isl_val *val = isl_constraint_get_coefficient_val(cst_i, isl_dim_set, i); const char *name = isl_constraint_get_dim_name(cst_i, isl_dim_set, i); if (!isl_val_is_zero(val)) { if (!is_first) { p = isl_printer_print_str(p, " + "); is_first = 0; } if (!isl_val_is_one(val)) { p = isl_printer_print_val(p, val); p = isl_printer_print_str(p, " * "); } p = isl_printer_print_str(p, name); if (is_first) is_first = 0; } isl_val_free(val); } for (int i = 0; i < isl_constraint_dim(cst_i, isl_dim_param); i++) { isl_val *val = isl_constraint_get_coefficient_val(cst_i, isl_dim_param, i); const char *name = isl_constraint_get_dim_name(cst_i, isl_dim_param, i); if (!isl_val_is_zero(val)) { if (!is_first) { p = isl_printer_print_str(p, " + "); is_first = 0; } if (!isl_val_is_one(val)) { p = isl_printer_print_val(p, val); p = isl_printer_print_str(p, " * "); } p = isl_printer_print_str(p, name); if (is_first) is_first = 0; } isl_val_free(val); } isl_val *cst_val = isl_constraint_get_constant_val(cst_i); if (!isl_val_is_zero(cst_val)) { p = isl_printer_print_str(p, " + "); p = isl_printer_print_val(p, cst_val); } isl_val_free(cst_val); if (isl_constraint_is_equality(cst_i)) { p = isl_printer_print_str(p, " == 0"); } else { p = isl_printer_print_str(p, " >= 0"); } isl_constraint_free(cst_i); if (multi_cst) { p = isl_printer_print_str(p, ")"); } cst_id++; } isl_constraint_list_free(cst_list); if (multi_bset) { p = isl_printer_print_str(p, ")"); } isl_basic_set_free(bset); bset_id++; } isl_basic_set_list_free(bset_list); t2s_cst = isl_printer_get_str(p); isl_printer_free(p); return t2s_cst; } /* This function takes in the C statement "c_text" like * C[i][j] = 0 * and the iteration domain "domain", * prints out the T2S statement like * C(i,j) = select(i == 0 && j == 0, C(i,j-1), C(i,j)) */ static __isl_give char *c_to_t2s_stmt(__isl_take char *c_text, __isl_take isl_set *domain, int iter_num) { char ch; int loc = 0; int insert_select; char *iter_domain = NULL; char *t2s_text = NULL; isl_printer *p = isl_printer_to_str(isl_set_get_ctx(domain)); char *LHS_func = NULL; int at_LHS = 1; isl_ctx *ctx = isl_set_get_ctx(domain); isl_printer *p_LHS = isl_printer_to_str(ctx); /* Generate the iteration domain constructs in T2S format. */ if (!isl_set_is_empty(domain)) { /* Set up the iterators. */ for (int i = 0; i < isl_set_dim(domain, isl_dim_set); i++) { char iter_name[100]; sprintf(iter_name, "c%d", i); isl_id *id_i = isl_id_alloc(ctx, iter_name, NULL); domain = isl_set_set_dim_id(domain, isl_dim_set, i, id_i); } iter_domain = isl_set_to_t2s_format(domain); } while ((ch = c_text[loc]) != '\0') { if (ch == '=') { while((ch = c_text[++loc]) == ' ') { ; } p = isl_printer_print_str(p, "= "); if (iter_domain) { p = isl_printer_print_str(p, "select("); p = isl_printer_print_str(p, iter_domain); p = isl_printer_print_str(p, ", "); } } else if (ch == ';') { if (iter_domain) { // p = isl_printer_print_str(p, ", "); // p = isl_printer_print_str(p, LHS_func); p = isl_printer_print_str(p, ")"); } } else if (ch == '[') { isl_printer *p_func = isl_printer_to_str(isl_set_get_ctx(domain)); p_func = isl_printer_print_str(p_func, "("); loc++; int dim_cnt = 0; while((ch = c_text[loc]) && (dim_cnt < iter_num)) { if (ch == ']') { dim_cnt++; if (c_text[loc + 1] == '[') p_func = isl_printer_print_str(p_func, ", "); else p_func = isl_printer_print_str(p_func, ")"); } else if (ch == '[') { loc++; continue; } else { char ch_str[2]; ch_str[0] = ch; ch_str[1] = '\0'; p_func = isl_printer_print_str(p_func, ch_str); } loc++; } char *func_str = isl_printer_get_str(p_func); p = isl_printer_print_str(p, func_str); if (at_LHS) { p_LHS = isl_printer_print_str(p_LHS, func_str); LHS_func = isl_printer_get_str(p_LHS); at_LHS = 0; } free(func_str); isl_printer_free(p_func); } char ch_str[2]; ch_str[0] = ch; ch_str[1] = '\0'; p = isl_printer_print_str(p, ch_str); if (at_LHS) { p_LHS = isl_printer_print_str(p_LHS, ch_str); } loc++; } t2s_text = isl_printer_get_str(p); isl_printer_free(p); isl_printer_free(p_LHS); free(iter_domain); free(LHS_func); free(c_text); isl_set_free(domain); return t2s_text; } /* Generate the number denotes how many times the given function has been updated. */ static int get_t2s_URE_update_level(struct t2s_URE **UREs, int URE_num, __isl_take char *func_name) { char **URE_names = NULL; if (URE_num > 0) { URE_names = (char **)malloc(URE_num * sizeof(char *)); for (int i = 0; i < URE_num; i++) { URE_names[i] = strdup(UREs[i]->name); } } int update_level = -1; for (int i = 0; i < URE_num; i++) { char *cur_name = URE_names[i]; if (strlen(cur_name) >= strlen(func_name)) { char cur_name_prefix[strlen(cur_name) + 1]; char ch; int loc = 0; while ((ch = cur_name[loc]) != '\0') { if (ch == '.') break; else { cur_name_prefix[loc] = cur_name[loc]; loc++; } } cur_name_prefix[loc] = '\0'; if (!strcmp(cur_name_prefix, func_name)) update_level++; } } if (URE_num > 0) { for (int i = 0; i < URE_num; i++) { free(URE_names[i]); } } free(URE_names); free(func_name); return update_level; } /* Given the func name, update the URE name and the update_level. */ static __isl_give struct t2s_URE *create_t2s_URE(__isl_keep struct t2s_URE **UREs, int URE_num, __isl_take char *func_name, __isl_take char *URE_text, int d, isl_ctx *ctx) { struct t2s_URE *URE = (struct t2s_URE *)malloc(sizeof(struct t2s_URE)); char **URE_names = NULL; if (URE_num > 0) { URE_names = (char **)malloc(URE_num * sizeof(char *)); for (int i = 0; i < URE_num; i++) { URE_names[i] = strdup(UREs[i]->name); } } int update_level = -1; for (int i = 0; i < URE_num; i++) { char *cur_name = URE_names[i]; if (strlen(cur_name) >= strlen(func_name)) { char cur_name_prefix[strlen(cur_name) + 1]; char ch; int loc = 0; while ((ch = cur_name[loc]) != '\0') { if (ch == '.') break; else { cur_name_prefix[loc] = cur_name[loc]; loc++; } } cur_name_prefix[loc] = '\0'; if (!strcmp(cur_name_prefix, func_name)) update_level++; } } isl_printer *p = isl_printer_to_str(ctx); p = isl_printer_print_str(p, func_name); if (update_level >= 0) { p = isl_printer_print_str(p, ".update("); p = isl_printer_print_int(p, update_level); p = isl_printer_print_str(p, ")"); } URE->name = isl_printer_get_str(p); isl_printer_free(p); URE->d = d; URE->text = URE_text; URE->update_level = update_level; if (URE_num > 0) { for (int i = 0; i < URE_num; i++) { free(URE_names[i]); } } free(URE_names); free(func_name); return URE; } /* Create the T2S URE from the statement text. */ static isl_stat create_t2s_URE_from_text(struct t2s_data *data, __isl_take char *URE_text, int d, isl_ctx *ctx) { char *func_name; char ch; int loc = 0; isl_printer *p = isl_printer_to_str(ctx); char *func_name_tmp; struct t2s_URE **UREs = data->URE; int URE_num = data->URE_num; while ((ch = URE_text[loc]) != '\0') { if (ch == '=') break; char ch_arr[2]; ch_arr[0] = ch; ch_arr[1] = '\0'; p = isl_printer_print_str(p, ch_arr); loc++; } func_name_tmp = isl_printer_get_str(p); isl_printer_free(p); loc = strlen(func_name_tmp) - 1; while((ch = func_name_tmp[loc--]) != ' ') { ; } char *func_decl = (char *)malloc(sizeof(char) * (loc + 1 + 1)); strncpy(func_decl, func_name_tmp, loc + 1); func_decl[loc + 1] = '\0'; while((ch = func_name_tmp[loc--]) != '(') { ; } func_name = (char *)malloc(sizeof(char) * (loc + 1 + 1)); strncpy(func_name, func_name_tmp, loc + 1); func_name[loc + 1] = '\0'; free(func_name_tmp); int update_level = get_t2s_URE_update_level(UREs, URE_num, strdup(func_name)); // if (update_level == -1) { // p = isl_printer_to_str(ctx); // p = isl_printer_print_str(p, func_decl); // p = isl_printer_print_str(p, " = 0;\n"); // char *init_URE_text = isl_printer_get_str(p); // isl_printer_free(p); // // data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); // data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(func_name), init_URE_text, d, ctx); // data->URE_num++; // } /* Add the statement URE. */ data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(func_name), URE_text, d, ctx); data->URE_num++; free(func_name); free(func_decl); return isl_stat_ok; } /* Free up the t2s_stmt_data. */ static __isl_null struct t2s_stmt_data *t2s_stmt_data_free(__isl_take struct t2s_stmt_data *d) { if (!d) return NULL; for (int i = 0; i < d->stmt_num; i++) { ppcg_stmt_free(d->stmts[i]); isl_set_free(d->stmt_domain[i]); } free(d->stmts); free(d->stmt_domain); isl_set_free(d->stmt_anchor_domain); isl_pw_multi_aff_free(d->iterator_map); for (int i = 0; i < d->n_acc_group; i++) { for (int j = 0; j < d->n_dep_per_acc_group[i]; j++) { polysa_dep_free(d->stmt_deps[i][j]); } free(d->stmt_deps[i]); } free(d->stmt_deps); free(d->n_dep_per_acc_group); free(d); return NULL; } /* Buggy Implementation. */ ///* For each user statement, there will be multiple T2S UREs generated given different // * dependences. To improve the hardware efficiency and code readability, there UREs // * will be merged into one UREs in this function. // * For example, given two UREs: // * A(i, j, k) = select(D1, A(i, j, k) + B(i, j, k)); // * A(i, j, k) = select(D2, A(i, j, k - 1) + B(i, j, k)); // * We will merge them into one URE below: // * A(i, j, k) = select(D1, A(i, j, k), select(D2, A(i, j, k - 1))) + // * select(D1, B(i, j, k), select(D2, B(i, j, k))); // */ //char *merge_t2s_stmt_text(__isl_take char **stmt_texts, int n, isl_ctx *ctx) { // char **iter_domain = (char **)malloc(sizeof(char *) * n); // int n_func = 0; // // /* Collect number of functions in the statement. */ // char *text = stmt_texts[0]; // char ch; // int loc = 0; // bool is_func = true; // while((ch = text[loc]) != '\0') { // if (ch == '(') { // ch = text[++loc]; // while(ch != '(' && ch != ')') { // ch = text[++loc]; // if (ch == '=' || ch == '>' || ch == '<') // is_func = false; // } // if (ch == ')') { // if (is_func) // n_func++; // is_func = true; // } else if (ch == '(') { // loc--; // } // } // loc++; // } // // char ***func = (char ***)malloc(sizeof(char **) * n_func); // for (int i = 0; i < n_func; i++) { // func[i] = (char **)malloc(sizeof(char *) * n); // } // int* func_offset = (int *)malloc(sizeof(int) * n_func); // // /* Collect all the iteration domains and func names. */ // for (int i = 0; i < n; i++) { // char *text = stmt_texts[i]; // char ch; // int loc = 0; // int func_id = 0; // while((ch = text[loc]) != '\0') { // if (ch == 's') { // char token[6]; // if (loc + 6 <= strlen(text)) { // strncpy(token, text + loc, 6); // } // if (!strcmp(token, "select")) { // /* Collect the iteration domain. */ // isl_printer *p_str = isl_printer_to_str(ctx); // loc += 6; // loc += 1; // while (ch = text[loc] != ',') { // char ch_arr[2]; // ch_arr[0] = ch; // ch_arr[1] = '\0'; // p_str = isl_printer_print_str(p_str, ch_arr); // loc++; // } // iter_domain[i] = isl_printer_get_str(p_str); // isl_printer_free(p_str); // } // } // // /* Collect the func names. */ // if (ch == '(') { // while (loc >= 0 && ((ch = text[loc]) != ' ')) // loc--; // loc++; // isl_printer *p_str = isl_printer_to_str(ctx); // while((ch = text[loc]) != '(') { // char ch_arr[2]; // ch_arr[0] = ch; // ch_arr[1] = '\0'; // p_str = isl_printer_print_str(p_str, ch_arr); // loc++; // } // // int loc_cur = loc; // char ch_arr[2]; // ch_arr[0] = ch; // ch_arr[1] = '\0'; // p_str = isl_printer_print_str(p_str, ch_arr); // loc++; // while((ch = text[loc]) != ')') { // char ch_arr[2]; // ch_arr[0] = ch; // ch_arr[1] = '\0'; // p_str = isl_printer_print_str(p_str, ch_arr); // if (ch == '(') { // loc--; // p_str = isl_printer_free(p_str); // break; // } // loc++; // } // if (p_str) { // p_str = isl_printer_print_str(p_str, ")"); // func[func_id][i] = isl_printer_get_str(p_str); // if (i == 0) // func_offset[func_id] = loc - strlen(func[func_id][i]) + 1; // func_id++; // p_str = isl_printer_free(p_str); // } // } // loc++; // } // } // // /* Scan through the statement text and plug in the functions and domains. */ // loc = 0; // text = stmt_texts[0]; // isl_printer *p_str = isl_printer_to_str(ctx); // int func_cnt = 0; // while ((ch = text[loc]) != '\0') { // if (loc == func_offset[func_cnt]) { // if (func_cnt == 0) // p_str = isl_printer_print_str(p_str, func[func_cnt][0]); // else { // for (int i = 0; i < n; i++) { // if (i > 0) // p_str = isl_printer_print_str(p_str, ", "); // p_str = isl_printer_print_str(p_str, "select("); // p_str = isl_printer_print_str(p_str, iter_domain[i]); // p_str = isl_printer_print_str(p_str, ", "); // p_str = isl_printer_print_str(p_str, func[func_cnt][i]); // } // for (int i = 0; i < n; i++) { // p_str = isl_printer_print_str(p_str, ")"); // } // } // loc += strlen(func[func_cnt][0]); // func_cnt++; // } else { // char ch_arr[2]; // ch_arr[0] = ch; // ch_arr[1] = '\0'; // p_str = isl_printer_print_str(p_str, ch_arr); // } // loc++; // } // // char *merge_text = isl_printer_get_str(p_str); // isl_printer_free(p_str); // for (int i = 0; i < n; i++) { // free(stmt_texts[i]); // } // free(stmt_texts); // // return merge_text; //} /* Buggy implementation. */ ///* Transform each user statement in the original program to a T2S URE // * w/ URE simplification. // * In this function, only one URE is generated for each user statement. // */ //static __isl_give isl_schedule_node *gen_stmt_text_single(__isl_take isl_schedule_node *node, void *user) //{ // struct ppcg_stmt *stmt; // isl_set *domain; // isl_space *space; // isl_id *id; // struct t2s_data *data = user; // struct t2s_stmt_data *stmt_data; // // if (!node) // return NULL; // // if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) // return node; // // isl_ctx *ctx = isl_schedule_node_get_ctx(node); // // /* Find the stmt. */ // stmt = isl_calloc_type(data->ctx, struct ppcg_stmt); // domain = isl_set_from_union_set(isl_schedule_node_get_domain(node)); // space = isl_set_get_space(domain); // id = isl_space_get_tuple_id(space, isl_dim_set); // stmt->stmt = find_stmt(data->scop, id); // isl_space_free(space); // isl_set_free(domain); // // /* Decide if there will be multiple T2S stmts generated for one stmt. // * Construct the unique acc->func mapping for each T2S stmts.*/ // stmt_data = isl_calloc_type(data->ctx, struct t2s_stmt_data); // stmt_data->stmt_num = 0; // stmt_data->stmts = NULL; // stmt_data->stmt_domain = NULL; // stmt_data->stmt_deps = NULL; // stmt_data->n_acc_group = 0; // stmt_data->n_dep_per_acc_group = 0; // stmt_data->dep_stmt_pair = NULL; // stmt_data->iterator_map = NULL; // isl_set_list *stmt_domain_list = isl_union_set_get_set_list(data->stmt_domain); // for (int i = 0; i < isl_union_set_n_set(data->stmt_domain); i++) { // isl_set *stmt_domain_i = isl_set_list_get_set(stmt_domain_list, i); // isl_space *space_i = isl_set_get_space(stmt_domain_i); // isl_id *id_i = isl_space_get_tuple_id(space_i, isl_dim_set); // if (id_i == id) // stmt_data->stmt_anchor_domain = isl_set_copy(stmt_domain_i); // isl_set_free(stmt_domain_i); // isl_space_free(space_i); // isl_id_free(id_i); // } // isl_set_list_free(stmt_domain_list); // isl_id_free(id); // // data->stmt_data = stmt_data; // /* Extract the ref2expr for each access. */ // extract_t2s_stmt_access(stmt, data); // // data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + data->stmt_data->stmt_num)); // char **stmt_texts = isl_calloc_array(data->ctx, char *, data->stmt_data->stmt_num); // // /* Print the stmt to data->t2s_stmt_text and update data->t2s_stmt_num. */ // for (int i = 0; i < data->stmt_data->stmt_num; i++) { // isl_printer *p_str = isl_printer_to_str(data->ctx); // p_str = isl_printer_set_output_format(p_str, ISL_FORMAT_C); // struct ppcg_stmt *stmt_i = data->stmt_data->stmts[i]; // p_str = pet_stmt_print_body(stmt_i->stmt, p_str, stmt_i->ref2expr); // char *stmt_text = isl_printer_get_str(p_str); // stmt_texts[i] = c_to_t2s_stmt(stmt_text, isl_set_copy(data->stmt_data->stmt_domain[i]), data->iter_num); //// create_t2s_URE_from_text(data, stmt_text, 0, ctx); // isl_printer_free(p_str); // } // char *merged_stmt_text = merge_t2s_stmt_text(stmt_texts, data->stmt_data->stmt_num, data->ctx); // create_t2s_URE_from_text(data, merged_stmt_text, 0, ctx); // // data->stmt_data = t2s_stmt_data_free(stmt_data); // // return node; //} /* Transform each user statement in the original program to a T2S URE. * w/o URE simplification. * In this function, multiple UREs can be generated for each user statement. */ static __isl_give isl_schedule_node *gen_stmt_text(__isl_take isl_schedule_node *node, void *user) { struct ppcg_stmt *stmt; isl_set *domain; isl_space *space; isl_id *id; struct t2s_data *data = user; struct t2s_stmt_data *stmt_data; if (!node) return NULL; if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) return node; isl_ctx *ctx = isl_schedule_node_get_ctx(node); // // debug // isl_printer *p = isl_printer_to_file(data->ctx, stdout); // p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK); // p = isl_printer_print_schedule_node(p, node); // printf("\n"); // // debug /* Find the stmt. */ stmt = isl_calloc_type(data->ctx, struct ppcg_stmt); domain = isl_set_from_union_set(isl_schedule_node_get_domain(node)); space = isl_set_get_space(domain); id = isl_space_get_tuple_id(space, isl_dim_set); stmt->stmt = find_stmt(data->scop, id); isl_space_free(space); isl_set_free(domain); /* Decide if there will be multiple T2S stmts generated for one stmt. * Construct the unique acc->func mapping for each T2S stmts.*/ stmt_data = isl_calloc_type(data->ctx, struct t2s_stmt_data); stmt_data->stmt_num = 0; stmt_data->stmts = NULL; stmt_data->stmt_domain = NULL; stmt_data->stmt_deps = NULL; stmt_data->n_acc_group = 0; stmt_data->n_dep_per_acc_group = 0; stmt_data->dep_stmt_pair = NULL; stmt_data->iterator_map = NULL; isl_set_list *stmt_domain_list = isl_union_set_get_set_list(data->stmt_domain); for (int i = 0; i < isl_union_set_n_set(data->stmt_domain); i++) { isl_set *stmt_domain_i = isl_set_list_get_set(stmt_domain_list, i); isl_space *space_i = isl_set_get_space(stmt_domain_i); isl_id *id_i = isl_space_get_tuple_id(space_i, isl_dim_set); if (id_i == id) stmt_data->stmt_anchor_domain = isl_set_copy(stmt_domain_i); isl_set_free(stmt_domain_i); isl_space_free(space_i); isl_id_free(id_i); } isl_set_list_free(stmt_domain_list); isl_id_free(id); // // debug // isl_printer *p = isl_printer_to_file(data->ctx, stdout); // p = isl_printer_print_set(p, stmt_data->stmt_anchor_domain); // printf("\n"); // // debug data->stmt_data = stmt_data; /* Extract the ref2expr for each access. */ extract_t2s_stmt_access(stmt, data); data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + data->stmt_data->stmt_num)); /* Print the stmt to data->t2s_stmt_text and update data->t2s_stmt_num. */ for (int i = 0; i < data->stmt_data->stmt_num; i++) { isl_printer *p_str = isl_printer_to_str(data->ctx); p_str = isl_printer_set_output_format(p_str, ISL_FORMAT_C); struct ppcg_stmt *stmt_i = data->stmt_data->stmts[i]; p_str = pet_stmt_print_body(stmt_i->stmt, p_str, stmt_i->ref2expr); // // debug // isl_printer *p_debug = isl_printer_to_file(data->ctx, stdout); // p_debug = isl_printer_print_set(p_debug, data->stmt_data->stmt_domain[i]); // printf("\n"); // // debug char *stmt_text = isl_printer_get_str(p_str); stmt_text = c_to_t2s_stmt(stmt_text, isl_set_copy(data->stmt_data->stmt_domain[i]), data->iter_num); create_t2s_URE_from_text(data, stmt_text, 0, ctx); isl_printer_free(p_str); } data->stmt_data = t2s_stmt_data_free(stmt_data); return node; } /* Generate the array access from isl_multi_pw_aff "mpa". */ static __isl_give char *array_acc_from_multi_pw_aff(__isl_take isl_multi_pw_aff *mpa) { isl_ctx *ctx; ctx = isl_multi_pw_aff_get_ctx(mpa); isl_space *space = isl_multi_pw_aff_get_space(mpa); const char *array_name = isl_space_get_tuple_name(space, isl_dim_out); isl_printer *p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_multi_pw_aff(p_str, mpa); char *mpa_str = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_str(p_str, array_name); char ch; int loc = 0; while ((ch = mpa_str[loc]) != '\0') { if (ch == '(') { while((ch = mpa_str[++loc]) == '(') ; loc--; p_str = isl_printer_print_str(p_str, "["); while((ch = mpa_str[++loc]) != ')') { char ch_arr[2]; ch_arr[0] = ch; ch_arr[1] = '\0'; p_str = isl_printer_print_str(p_str, ch_arr); } p_str = isl_printer_print_str(p_str, "]"); } loc++; } char *acc_str = isl_printer_get_str(p_str); free(mpa_str); isl_printer_free(p_str); isl_multi_pw_aff_free(mpa); isl_space_free(space); return acc_str; } /* Set the iterator names in the target domain. */ static __isl_give isl_set *t2s_set_set_iters(__isl_take isl_set *s) { isl_ctx *ctx = isl_set_get_ctx(s); for (int i = 0; i < isl_set_dim(s, isl_dim_set); i++) { char iter_name[100]; sprintf(iter_name, "c%d", i); isl_id *id_i = isl_id_alloc(ctx, iter_name, NULL); s = isl_set_set_dim_id(s, isl_dim_set, i, id_i); } return s; } /* Set up the iterator names. */ static __isl_give isl_multi_pw_aff *t2s_set_multi_pw_aff_iters(__isl_take isl_multi_pw_aff *mpa) { isl_ctx *ctx = isl_multi_pw_aff_get_ctx(mpa); for (int i = 0; i < isl_multi_pw_aff_dim(mpa, isl_dim_in); i++) { char iter_name[100]; sprintf(iter_name, "c%d", i); isl_id *id_i = isl_id_alloc(ctx, iter_name, NULL); mpa = isl_multi_pw_aff_set_dim_id(mpa, isl_dim_in, i, id_i); } return mpa; } /* Create UREs for live-in accesses associated with RAR deps. */ static int t2s_rar_URE_access(__isl_keep pet_expr *expr, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data = data->stmt_data; isl_multi_pw_aff *index; isl_id *id; id = isl_id_copy(expr->acc.ref_id); index = isl_multi_pw_aff_copy(expr->acc.index); struct polysa_dep *dep; int n; isl_ctx *ctx = data->ctx; char *URE_text; for (n = 0; n < data->ndeps; n++) { dep = data->deps[n]; if (dep->dest == id && dep->type == POLYSA_DEP_RAR) break; } if (n != data->ndeps) { isl_set *stmt_domain = isl_set_copy(stmt_data->stmt_anchor_domain); isl_set *dep_dest_domain = isl_set_copy(dep->dest_sched_domain); /* Generate the init domain */ isl_set *init_domain = isl_set_subtract(stmt_domain, isl_set_copy(dep_dest_domain)); isl_set *anchor_domain = isl_set_copy(data->anchor_domain); anchor_domain = isl_set_set_tuple_name(anchor_domain, isl_set_get_tuple_name(init_domain)); init_domain = isl_set_gist(init_domain, isl_set_copy(anchor_domain)); isl_set *reuse_domain = isl_set_gist(dep_dest_domain, anchor_domain); /* Peel off the scalar dimensions */ init_domain = t2s_peel_off_scalar_dims(init_domain, data->schedule); reuse_domain = t2s_peel_off_scalar_dims(reuse_domain, data->schedule); /* Set up the iterator names. */ init_domain = t2s_set_set_iters(init_domain); reuse_domain = t2s_set_set_iters(reuse_domain); char *init_domain_str = isl_set_to_t2s_format(init_domain); isl_set_free(init_domain); char *reuse_domain_str = isl_set_to_t2s_format(reuse_domain); isl_set_free(reuse_domain); /* Generate the func name .*/ isl_id *func = isl_id_to_id_get(data->ref2func, isl_id_copy(id)); isl_printer *p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); char *func_name = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); p_str = isl_printer_print_str(p_str, "("); for (int i = 0; i < data->iter_num; i++) { if (i > 0) { p_str = isl_printer_print_str(p_str, ", "); } char iter_name[100]; sprintf(iter_name, "c%d", i); p_str = isl_printer_print_str(p_str, iter_name); } p_str = isl_printer_print_str(p_str, ")"); char *func_str = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); p_str = isl_printer_print_str(p_str, "("); for (int i = 0; i < data->iter_num; i++) { if (i > 0) { p_str = isl_printer_print_str(p_str, ", "); } char iter_name[100]; isl_val *ele = isl_vec_get_element_val(dep->disvec, i); if (isl_val_is_zero(ele)) { sprintf(iter_name, "c%d", i); } else { sprintf(iter_name, "c%d - %ld", i, isl_val_get_num_si(ele)); } p_str = isl_printer_print_str(p_str, iter_name); isl_val_free(ele); } p_str = isl_printer_print_str(p_str, ")"); char *reuse_func_str = isl_printer_get_str(p_str); isl_printer_free(p_str); /* Generate the transformed index. */ isl_multi_pw_aff *trans_index = isl_multi_pw_aff_copy(index); trans_index = isl_multi_pw_aff_pullback_pw_multi_aff(trans_index, isl_pw_multi_aff_copy(stmt_data->iterator_map)); /* Set up the iterator names. */ trans_index = t2s_set_multi_pw_aff_iters(trans_index); char *acc_str = array_acc_from_multi_pw_aff(trans_index); /* Generate the URE. */ int update_level = get_t2s_URE_update_level(data->URE, data->URE_num, strdup(func_name)); /* Comment out. The latest T2S no longer requires this. */ // if (update_level == -1) { // p_str = isl_printer_to_str(ctx); // p_str = isl_printer_print_str(p_str, func_str); // p_str = isl_printer_print_str(p_str, " = 0;\n"); // URE_text = isl_printer_get_str(p_str); // isl_printer_free(p_str); // // data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); // data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(func_name), URE_text, 0, ctx); // data->URE_num++; // } p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_str(p_str, func_str); p_str = isl_printer_print_str(p_str, " = "); p_str = isl_printer_print_str(p_str, "select("); p_str = isl_printer_print_str(p_str, init_domain_str); p_str = isl_printer_print_str(p_str, ", "); p_str = isl_printer_print_str(p_str, acc_str); p_str = isl_printer_print_str(p_str, ", select("); p_str = isl_printer_print_str(p_str, reuse_domain_str); p_str = isl_printer_print_str(p_str, ", "); p_str = isl_printer_print_str(p_str, reuse_func_str); // p_str = isl_printer_print_str(p_str, ", "); // p_str = isl_printer_print_str(p_str, func_str); p_str = isl_printer_print_str(p_str, "));\n"); URE_text = isl_printer_get_str(p_str); isl_printer_free(p_str); // data->t2s_stmt_text = (char **)realloc(data->t2s_stmt_text, sizeof(char *) * (data->t2s_stmt_num + 1)); // data->t2s_stmt_text[data->t2s_stmt_num] = URE_text; // data->t2s_stmt_num++; data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(func_name), URE_text, 0, ctx); data->URE_num++; isl_id_free(func); free(func_str); free(func_name); free(init_domain_str); free(acc_str); free(reuse_domain_str); free(reuse_func_str); } isl_id_free(id); isl_multi_pw_aff_free(index); return 0; } /* Extract UREs for live-in accesses. */ static isl_stat extract_rar_URE(__isl_take struct ppcg_stmt *stmt, struct t2s_data *data) { pet_tree_foreach_access_expr(stmt->stmt->body, &t2s_rar_URE_access, data); ppcg_stmt_free(stmt); return isl_stat_ok; } /* Generate the reuse (RAR) UREs for the operands in the user statements. */ static __isl_give isl_schedule_node *gen_op_stmt_text(__isl_take isl_schedule_node *node, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data; struct ppcg_stmt *stmt; isl_set *domain; isl_space *space; isl_id *id; if (!node) return NULL; if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) return node; /* Find the statement. */ stmt = isl_calloc_type(data->ctx, struct ppcg_stmt); domain = isl_set_from_union_set(isl_schedule_node_get_domain(node)); space = isl_set_get_space(domain); id = isl_space_get_tuple_id(space, isl_dim_set); stmt->stmt = find_stmt(data->scop, id); isl_space_free(space); isl_set_free(domain); stmt_data = isl_calloc_type(data->ctx, struct t2s_stmt_data); stmt_data->stmt_num = 0; stmt_data->stmts = NULL; stmt_data->stmt_domain = NULL; stmt_data->stmt_deps = NULL; stmt_data->n_acc_group = 0; stmt_data->n_dep_per_acc_group = 0; stmt_data->dep_stmt_pair = NULL; stmt_data->iterator_map = NULL; isl_set_list *stmt_domain_list = isl_union_set_get_set_list(data->stmt_domain); for (int i = 0; i < isl_union_set_n_set(data->stmt_domain); i++) { isl_set *stmt_domain_i = isl_set_list_get_set(stmt_domain_list, i); isl_space *space_i = isl_set_get_space(stmt_domain_i); isl_id *id_i = isl_space_get_tuple_id(space_i, isl_dim_set); if (id_i == id) stmt_data->stmt_anchor_domain = isl_set_copy(stmt_domain_i); isl_set_free(stmt_domain_i); isl_space_free(space_i); isl_id_free(id_i); } isl_set_list_free(stmt_domain_list); isl_id_free(id); data->stmt_data = stmt_data; /* Extract the schedule. */ isl_map *sched = isl_map_from_union_map(isl_schedule_node_get_prefix_schedule_relation(node)); sched = isl_map_reverse(sched); isl_pw_multi_aff *iterator_map = isl_pw_multi_aff_from_map(sched); data->stmt_data->iterator_map = iterator_map; extract_rar_URE(stmt, data); data->stmt_data = t2s_stmt_data_free(stmt_data); return node; } /* Create UREs for live-out accesses. */ static int t2s_drain_URE_access(__isl_keep pet_expr *expr, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data = data->stmt_data; isl_multi_pw_aff *index; isl_id *id; id = isl_id_copy(expr->acc.ref_id); index = isl_multi_pw_aff_copy(expr->acc.index); struct polysa_dep *dep; int n; isl_ctx *ctx = data->ctx; isl_set *writeout_domain = isl_set_copy(stmt_data->stmt_anchor_domain); int is_drain = 0; for (n = 0; n < data->ndeps; n++) { dep = data->deps[n]; if (dep->src == id && dep->type == POLYSA_DEP_WAW) { isl_set *dep_src_domain = isl_set_copy(dep->src_sched_domain); /* Generate the writeout domain */ writeout_domain = isl_set_subtract(writeout_domain, dep_src_domain); is_drain = 1; } } if (isl_set_is_empty(writeout_domain) || !is_drain) { isl_set_free(writeout_domain); isl_id_free(id); isl_multi_pw_aff_free(index); return 0; } else { isl_set *anchor_domain = isl_set_copy(data->anchor_domain); anchor_domain = isl_set_set_tuple_name(anchor_domain, isl_set_get_tuple_name(writeout_domain)); writeout_domain = isl_set_gist(writeout_domain, anchor_domain); /* Peel off the scalar dimensions. */ writeout_domain = t2s_peel_off_scalar_dims(writeout_domain, data->schedule); /* Set up the iterator names. */ writeout_domain = t2s_set_set_iters(writeout_domain); char *writeout_domain_str = isl_set_to_t2s_format(writeout_domain); isl_set_free(writeout_domain); /* Generate the func name .*/ isl_id *func = isl_id_to_id_get(data->ref2func, isl_id_copy(id)); isl_printer *p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); p_str = isl_printer_print_str(p_str, "_drain"); char *drain_func_name = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); p_str = isl_printer_print_str(p_str, "("); for (int i = 0; i < data->iter_num; i++) { if (i > 0) { p_str = isl_printer_print_str(p_str, ", "); } char iter_name[100]; sprintf(iter_name, "c%d", i); p_str = isl_printer_print_str(p_str, iter_name); } p_str = isl_printer_print_str(p_str, ")"); char *func_str = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_id(p_str, func); p_str = isl_printer_print_str(p_str, "_drain("); for (int i = 0; i < data->iter_num; i++) { if (i > 0) { p_str = isl_printer_print_str(p_str, ", "); } char iter_name[100]; sprintf(iter_name, "c%d", i); p_str = isl_printer_print_str(p_str, iter_name); } p_str = isl_printer_print_str(p_str, ")"); char *drain_func_str = isl_printer_get_str(p_str); isl_printer_free(p_str); // /* Generate the transformed index. */ // isl_multi_pw_aff *trans_index = isl_multi_pw_aff_copy(index); // trans_index = isl_multi_pw_aff_pullback_pw_multi_aff(trans_index, isl_pw_multi_aff_copy(stmt_data->iterator_map)); // // /* Set up the iterator names. */ // trans_index = t2s_set_multi_pw_aff_iters(trans_index); // char *acc_str = array_acc_from_multi_pw_aff(trans_index); /* Generate the URE. */ // p_str = isl_printer_to_str(ctx); // p_str = isl_printer_print_str(p_str, drain_func_str); // p_str = isl_printer_print_str(p_str, " = 0;\n"); // char *URE_text = isl_printer_get_str(p_str); // isl_printer_free(p_str); // data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); // data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(drain_func_name), URE_text, 1, ctx); // data->URE_num++; p_str = isl_printer_to_str(ctx); p_str = isl_printer_print_str(p_str, drain_func_str); p_str = isl_printer_print_str(p_str, " = "); p_str = isl_printer_print_str(p_str, "select("); p_str = isl_printer_print_str(p_str, writeout_domain_str); p_str = isl_printer_print_str(p_str, ", "); p_str = isl_printer_print_str(p_str, func_str); // p_str = isl_printer_print_str(p_str, ", "); // p_str = isl_printer_print_str(p_str, drain_func_str); p_str = isl_printer_print_str(p_str, ");\n"); char *URE_text = isl_printer_get_str(p_str); isl_printer_free(p_str); // data->t2s_stmt_text = (char **)realloc(data->t2s_stmt_text, sizeof(char *) * (data->t2s_stmt_num + 1)); // data->t2s_stmt_text[data->t2s_stmt_num] = URE_text; // data->t2s_stmt_num++; data->URE = (struct t2s_URE **)realloc(data->URE, sizeof(struct t2s_URE *) * (data->URE_num + 1)); data->URE[data->URE_num] = create_t2s_URE(data->URE, data->URE_num, strdup(drain_func_name), URE_text, 1, ctx); data->URE_num++; isl_id_free(func); free(drain_func_name); free(func_str); free(drain_func_str); free(writeout_domain_str); // free(acc_str); } isl_id_free(id); isl_multi_pw_aff_free(index); return 0; } /* Generate UREs for live-out accesses. */ static isl_stat extract_drain_URE(__isl_take struct ppcg_stmt *stmt, struct t2s_data *data) { pet_tree_foreach_access_expr(stmt->stmt->body, &t2s_drain_URE_access, data); ppcg_stmt_free(stmt); return isl_stat_ok; } /* Generate the drain UREs for the intermediate variables in the user statement. */ static __isl_give isl_schedule_node *gen_drain_stmt_text(__isl_take isl_schedule_node *node, void *user) { struct t2s_data *data = user; struct t2s_stmt_data *stmt_data; struct ppcg_stmt *stmt; isl_set *domain; isl_space *space; isl_id *id; if (!node) return NULL; if (isl_schedule_node_get_type(node) != isl_schedule_node_leaf) return node; /* Find the statement. */ stmt = isl_calloc_type(data->ctx, struct ppcg_stmt); domain = isl_set_from_union_set(isl_schedule_node_get_domain(node)); space = isl_set_get_space(domain); id = isl_space_get_tuple_id(space, isl_dim_set); stmt->stmt = find_stmt(data->scop, id); isl_space_free(space); isl_set_free(domain); stmt_data = isl_calloc_type(data->ctx, struct t2s_stmt_data); stmt_data->stmt_num = 0; stmt_data->stmts = NULL; stmt_data->stmt_domain = NULL; stmt_data->stmt_deps = NULL; stmt_data->n_acc_group = 0; stmt_data->n_dep_per_acc_group = 0; stmt_data->dep_stmt_pair = NULL; stmt_data->iterator_map = NULL; isl_set_list *stmt_domain_list = isl_union_set_get_set_list(data->stmt_domain); for (int i = 0; i < isl_union_set_n_set(data->stmt_domain); i++) { isl_set *stmt_domain_i = isl_set_list_get_set(stmt_domain_list, i); isl_space *space_i = isl_set_get_space(stmt_domain_i); isl_id *id_i = isl_space_get_tuple_id(space_i, isl_dim_set); if (id_i == id) { stmt_data->stmt_anchor_domain = isl_set_copy(stmt_domain_i); } isl_set_free(stmt_domain_i); isl_space_free(space_i); isl_id_free(id_i); } isl_set_list_free(stmt_domain_list); isl_id_free(id); data->stmt_data = stmt_data; /* Extract the schedule. */ isl_map *sched = isl_map_from_union_map(isl_schedule_node_get_prefix_schedule_relation(node)); sched = isl_map_reverse(sched); isl_pw_multi_aff *iterator_map = isl_pw_multi_aff_from_map(sched); data->stmt_data->iterator_map = iterator_map; extract_drain_URE(stmt, data); data->stmt_data = t2s_stmt_data_free(stmt_data); return node; } /* Print UREs in T2S code. */ static __isl_give isl_schedule *gen_stmt_text_wrap(__isl_take isl_schedule *schedule, struct t2s_data *data) { data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "// UREs"); data->p = isl_printer_end_line(data->p); /* Generate the reuse (RAR) statement. */ schedule = isl_schedule_map_schedule_node_bottom_up(schedule, &gen_op_stmt_text, data); /* Traverse each statmenet, build the ppcg_stmt struct and update * the ref2expr using T2S functions. * Print the stmt to data->t2s_stmt_text. */ /* Option 1: Generate multiple UREs for one statement. */ schedule = isl_schedule_map_schedule_node_bottom_up(schedule, &gen_stmt_text, data); // /* Option 2: Generate single URE for one statement. (Buggy)*/ // schedule = isl_schedule_map_schedule_node_bottom_up(schedule, // &gen_stmt_text_single, data); /* Generate the drain statement. */ schedule = isl_schedule_map_schedule_node_bottom_up(schedule, &gen_drain_stmt_text, data); // /* Print out the T2S stmt texts. */ // for (int i = 0; i < data->t2s_stmt_num; i++) { //// data->p = isl_printer_start_line(data->p); // data->p = isl_printer_print_str(data->p, data->t2s_stmt_text[i]); //// data->p = isl_printer_end_line(data->p); // } /* Print out the URE texts. */ for (int i = 0; i < data->URE_num; i++) { data->p = isl_printer_print_str(data->p, data->URE[i]->text); } data->p = isl_printer_start_line(data->p); data->p = isl_printer_end_line(data->p); return schedule; } /* Extract the detailed information of iterators in the code, including: * - iterator name * - lower bound * - upper bound * - stride */ static isl_stat extract_iters(__isl_keep isl_schedule *schedule, struct t2s_data *data) { isl_ctx *ctx; isl_set *domain = isl_set_copy(data->anchor_domain); int iter_num = data->iter_num; ctx = isl_set_get_ctx(domain); // // debug // isl_printer *p = isl_printer_to_file(ctx, stdout); // p = isl_printer_print_set(p, domain); // printf("\n"); // // debug /* Peel off the scalar dimensions. */ domain = t2s_peel_off_scalar_dims(domain, schedule); // // debug //// isl_printer *p = isl_printer_to_file(ctx, stdout); // p = isl_printer_print_set(p, domain); // printf("\n"); // // debug data->iter = (struct polysa_iter **)malloc(sizeof(struct polysa_iter *) * iter_num); isl_map *domain_map = isl_map_from_range(isl_set_copy(domain)); isl_fixed_box *box = isl_map_get_range_simple_fixed_box_hull(domain_map); isl_multi_aff *offset; isl_multi_val *size; isl_map_free(domain_map); if (isl_fixed_box_is_valid(box)) { offset = isl_fixed_box_get_offset(box); size = isl_fixed_box_get_size(box); // // debug // p = isl_printer_print_multi_aff(p, offset); // printf("\n"); // p = isl_printer_print_multi_val(p, size); // printf("\n"); // // debug } for (int i = 0; i < data->iter_num; i++) { struct polysa_iter *iter = (struct polysa_iter *)malloc(sizeof(struct polysa_iter)); /* Stride. */ isl_stride_info *si; si = isl_set_get_stride_info(domain, i); isl_val *s = isl_stride_info_get_stride(si); // // debug // p = isl_printer_print_val(p, s); // printf("\n"); // // debug iter->stride = isl_val_get_num_si(s); isl_val_free(s); isl_stride_info_free(si); /* Name. */ char iter_name[100]; sprintf(iter_name, "c%d", i); iter->name = strdup(iter_name); char ts_iter_name[100]; if (data->prog->type == POLYSA_SA_TYPE_ASYNC) { if (i < data->prog->space_w) { sprintf(ts_iter_name, "sloop%d", i); } else { sprintf(ts_iter_name, "tloop%d", i - data->prog->space_w); } } else if (data->prog->type == POLYSA_SA_TYPE_SYNC) { if (i < data->prog->time_w) { sprintf(ts_iter_name, "tloop%d", i); } else { sprintf(ts_iter_name, "sloop%d", i - data->prog->time_w); } } iter->ts_name = strdup(ts_iter_name); /* Bounds. */ if (isl_fixed_box_is_valid(box)) { isl_aff *offset_i = isl_multi_aff_get_aff(offset, i); iter->lb = isl_aff_copy(offset_i); // // debug // p = isl_printer_print_aff(p, offset_i); // printf("\n"); // p = isl_printer_set_output_format(p, ISL_FORMAT_C); // p = isl_printer_print_aff(p, offset_i); // printf("\n"); // // debug isl_val *size_i = isl_multi_val_get_val(size, i); offset_i = isl_aff_add_constant_val(offset_i, size_i); offset_i = isl_aff_add_constant_si(offset_i, -1); iter->ub = offset_i; } data->iter[i] = iter; } if (isl_fixed_box_is_valid(box)) { isl_multi_aff_free(offset); isl_multi_val_free(size); } isl_fixed_box_free(box); isl_set_free(domain); return isl_stat_ok; } /* Extract the dependence (RAW, RAR, WAW) from the program. */ static __isl_give isl_schedule *extract_deps(__isl_take isl_schedule *schedule, struct t2s_data *data) { isl_schedule_node *band; isl_union_map *dep_flow; isl_union_map *dep_rar; isl_union_map *dep_waw; isl_union_map *dep_total; isl_basic_map_list *deps; int ndeps; isl_basic_map *dep_i; struct polysa_dep *p_dep_i; isl_vec *disvec; // // debug // isl_printer *p = isl_printer_to_file(data->ctx, stdout); // p = isl_printer_set_yaml_style(p, ISL_YAML_STYLE_BLOCK); // p = isl_printer_print_schedule(p, schedule); // printf("\n"); // // debug if (data->scop->options->t2s_tile && data->scop->options->t2s_tile_phase == 1) { band = isl_schedule_get_root(schedule); band = isl_schedule_node_child(band, 0); } else { band = get_outermost_permutable_node(schedule); } // // debug // p = isl_printer_print_schedule_node(p, band); // printf("\n"); // // debug dep_flow = data->scop->tagged_dep_flow; dep_rar = data->scop->tagged_dep_rar; dep_waw = data->scop->tagged_dep_waw; /* Add RAW deps. */ deps = isl_union_map_get_basic_map_list(dep_flow); ndeps = isl_union_map_n_basic_map(dep_flow); data->ndeps = ndeps; data->deps = (struct polysa_dep **)malloc(data->ndeps * sizeof(struct polysa_dep *)); for (int i = 0; i < ndeps; i++) { p_dep_i = (struct polysa_dep *)malloc(sizeof(struct polysa_dep)); dep_i = isl_basic_map_list_get_basic_map(deps, i); p_dep_i->isl_dep = isl_basic_map_copy(dep_i); isl_map *untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(isl_basic_map_copy(dep_i))); isl_basic_map *bmap_dep_i = isl_basic_map_from_map(untagged_dep_i); disvec = get_dep_dis_at_schedule(bmap_dep_i, schedule); /* The generated dependece distance vector contains the scalar dim, * we will need to peel them off. */ disvec = t2s_peel_off_scalar_dims_vec(disvec, schedule); // // debug // isl_printer *p = isl_printer_to_file(data->ctx, stdout); // p = isl_printer_print_basic_map(p, p_dep_i->isl_dep); // printf("\n"); // p = isl_printer_print_vec(p, disvec); // printf("\n"); // isl_printer_free(p); // // debug isl_basic_map_free(bmap_dep_i); isl_space *space = isl_basic_map_get_space(dep_i); isl_space *src_space = isl_space_unwrap(isl_space_domain(isl_space_copy(space))); isl_space *dest_space = isl_space_unwrap(isl_space_range(space)); isl_id *src_id = isl_space_get_tuple_id(src_space, isl_dim_out); isl_id *dest_id = isl_space_get_tuple_id(dest_space, isl_dim_out); isl_space_free(src_space); isl_space_free(dest_space); untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(dep_i)); isl_set *src_domain = isl_map_domain(isl_map_copy(untagged_dep_i)); isl_set *dest_domain = isl_map_range(untagged_dep_i); isl_union_map *sched = isl_schedule_node_get_subtree_schedule_union_map(band); isl_union_map *sched_src = isl_union_map_intersect_domain(isl_union_map_copy(sched), isl_union_set_from_set(isl_set_copy(src_domain))); isl_union_map *sched_dest = isl_union_map_intersect_domain(sched, isl_union_set_from_set(isl_set_copy(dest_domain))); p_dep_i->src_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_src)); p_dep_i->dest_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_dest)); /* Add the tuple name */ p_dep_i->src_sched_domain = isl_set_set_tuple_name(p_dep_i->src_sched_domain, isl_set_get_tuple_name(src_domain)); p_dep_i->dest_sched_domain = isl_set_set_tuple_name(p_dep_i->dest_sched_domain, isl_set_get_tuple_name(dest_domain)); isl_set_free(src_domain); isl_set_free(dest_domain); p_dep_i->src = src_id; p_dep_i->dest = dest_id; p_dep_i->disvec = disvec; p_dep_i->type = POLYSA_DEP_RAW; data->deps[i] = p_dep_i; } isl_basic_map_list_free(deps); /* Add RAR deps. */ deps = isl_union_map_get_basic_map_list(dep_rar); ndeps = isl_union_map_n_basic_map(dep_rar); data->deps = (struct polysa_dep **)realloc(data->deps, (data->ndeps + ndeps) * sizeof(struct polysa_dep *)); for (int i = 0; i < ndeps; i++) { p_dep_i = (struct polysa_dep *)malloc(sizeof(struct polysa_dep)); dep_i = isl_basic_map_list_get_basic_map(deps, i); p_dep_i->isl_dep = isl_basic_map_copy(dep_i); isl_map *untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(isl_basic_map_copy(dep_i))); isl_basic_map *bmap_dep_i = isl_basic_map_from_map(untagged_dep_i); disvec = get_dep_dis_at_schedule(bmap_dep_i, schedule); /* The generated dependece distance vector contains the scalar dim, * we will need to peel them off. */ disvec = t2s_peel_off_scalar_dims_vec(disvec, schedule); isl_basic_map_free(bmap_dep_i); isl_space *space = isl_basic_map_get_space(dep_i); isl_space *src_space = isl_space_unwrap(isl_space_domain(isl_space_copy(space))); isl_space *dest_space = isl_space_unwrap(isl_space_range(space)); isl_id *src_id = isl_space_get_tuple_id(src_space, isl_dim_out); isl_id *dest_id = isl_space_get_tuple_id(dest_space, isl_dim_out); isl_space_free(src_space); isl_space_free(dest_space); untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(dep_i)); isl_set *src_domain = isl_map_domain(isl_map_copy(untagged_dep_i)); isl_set *dest_domain = isl_map_range(untagged_dep_i); // // debug // isl_printer *p = isl_printer_to_file(data->ctx, stdout); // p = isl_printer_print_set(p, src_domain); // printf("\n"); // // debug isl_union_map *sched = isl_schedule_node_get_subtree_schedule_union_map(band); // // debug // p = isl_printer_print_union_map(p, sched); // printf("\n"); // // debug isl_union_map *sched_src = isl_union_map_intersect_domain(isl_union_map_copy(sched), isl_union_set_from_set(isl_set_copy(src_domain))); isl_union_map *sched_dest = isl_union_map_intersect_domain(sched, isl_union_set_from_set(isl_set_copy(dest_domain))); p_dep_i->src_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_src)); p_dep_i->dest_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_dest)); // // debug // p = isl_printer_print_set(p, p_dep_i->src_sched_domain); // printf("\n"); // // debug /* Add the tuple name */ p_dep_i->src_sched_domain = isl_set_set_tuple_name(p_dep_i->src_sched_domain, isl_set_get_tuple_name(src_domain)); p_dep_i->dest_sched_domain = isl_set_set_tuple_name(p_dep_i->dest_sched_domain, isl_set_get_tuple_name(dest_domain)); isl_set_free(src_domain); isl_set_free(dest_domain); p_dep_i->src = src_id; p_dep_i->dest = dest_id; p_dep_i->disvec = disvec; p_dep_i->type = POLYSA_DEP_RAR; data->deps[i + data->ndeps] = p_dep_i; } data->ndeps += ndeps; isl_basic_map_list_free(deps); /* Add WAW deps. */ deps = isl_union_map_get_basic_map_list(dep_waw); ndeps = isl_union_map_n_basic_map(dep_waw); data->deps = (struct polysa_dep **)realloc(data->deps, (data->ndeps + ndeps) * sizeof(struct polysa_dep *)); for (int i = 0; i < ndeps; i++) { p_dep_i = (struct polysa_dep *)malloc(sizeof(struct polysa_dep)); dep_i = isl_basic_map_list_get_basic_map(deps, i); p_dep_i->isl_dep = isl_basic_map_copy(dep_i); isl_map *untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(isl_basic_map_copy(dep_i))); isl_basic_map *bmap_dep_i = isl_basic_map_from_map(untagged_dep_i); disvec = get_dep_dis_at_schedule(bmap_dep_i, schedule); /* The generated dependece distance vector contains the scalar dim, * we will need to peel them off. */ disvec = t2s_peel_off_scalar_dims_vec(disvec, schedule); isl_basic_map_free(bmap_dep_i); isl_space *space = isl_basic_map_get_space(dep_i); isl_space *src_space = isl_space_unwrap(isl_space_domain(isl_space_copy(space))); isl_space *dest_space = isl_space_unwrap(isl_space_range(space)); isl_id *src_id = isl_space_get_tuple_id(src_space, isl_dim_out); isl_id *dest_id = isl_space_get_tuple_id(dest_space, isl_dim_out); isl_space_free(src_space); isl_space_free(dest_space); untagged_dep_i = isl_map_factor_domain(isl_map_from_basic_map(dep_i)); isl_set *src_domain = isl_map_domain(isl_map_copy(untagged_dep_i)); isl_set *dest_domain = isl_map_range(untagged_dep_i); isl_union_map *sched = isl_schedule_node_get_subtree_schedule_union_map(band); isl_union_map *sched_src = isl_union_map_intersect_domain(isl_union_map_copy(sched), isl_union_set_from_set(isl_set_copy(src_domain))); isl_union_map *sched_dest = isl_union_map_intersect_domain(sched, isl_union_set_from_set(isl_set_copy(dest_domain))); p_dep_i->src_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_src)); p_dep_i->dest_sched_domain = isl_set_from_union_set(isl_union_map_range(sched_dest)); /* Add the tuple name */ p_dep_i->src_sched_domain = isl_set_set_tuple_name(p_dep_i->src_sched_domain, isl_set_get_tuple_name(src_domain)); p_dep_i->dest_sched_domain = isl_set_set_tuple_name(p_dep_i->dest_sched_domain, isl_set_get_tuple_name(dest_domain)); isl_set_free(src_domain); isl_set_free(dest_domain); p_dep_i->src = src_id; p_dep_i->dest = dest_id; p_dep_i->disvec = disvec; p_dep_i->type = POLYSA_DEP_WAW; data->deps[i + data->ndeps] = p_dep_i; } data->ndeps += ndeps; isl_basic_map_list_free(deps); isl_schedule_node_free(band); return schedule; } static __isl_null struct t2s_URE *t2s_URE_free(__isl_take struct t2s_URE *u) { if (!u) return NULL; free(u->name); free(u->text); free(u); return NULL; } __isl_null struct t2s_data *t2s_data_free(__isl_take struct t2s_data *d) { if (!d) return NULL; isl_set_free(d->anchor_domain); isl_union_set_free(d->stmt_domain); isl_union_set_free(d->stmt_sim_domain); for (int i = 0; i < d->t2s_stmt_num; i++) { free(d->t2s_stmt_text[i]); } free(d->t2s_stmt_text); for (int i = 0; i < d->URE_num; i++) { t2s_URE_free(d->URE[i]); } free(d->URE); for (int i = 0; i < d->iter_num; i++) { polysa_iter_free(d->iter[i]); } free(d->iter); isl_printer_free(d->p); for (int i = 0; i < d->ndeps; i++) { polysa_dep_free(d->deps[i]); } free(d->deps); t2s_stmt_data_free(d->stmt_data); isl_id_to_id_free(d->ref2func); for (int i = 0; i < d->n_array; i++) { struct t2s_array_info *array = &d->array[i]; for (int j = 0; j < array->n_group; j++) { t2s_array_ref_group_free(array->groups[j]); } free(array->groups); } free(d->array); t2s_group_data_free(d->group_data); isl_id_list_free(d->func_ids); free(d); return NULL; } /* Generate T2S headers. */ static isl_stat gen_t2s_headers(struct t2s_data *data) { isl_printer *p = data->p; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "#include \"Halide.h\""); p = isl_printer_end_line(p); p = isl_printer_print_str(p, "#include <iostream>"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_print_str(p, "using namespace Halide;"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_print_str(p, "using namespace std;\n"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); return isl_stat_ok; } /* Generate T2S inputs. */ static isl_stat gen_t2s_inputs(struct t2s_data *data) { isl_printer *p = data->p; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "// Inputs (Fill in manually)"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); } /* Generate T2S variable declarations. */ static isl_stat gen_t2s_vars(struct t2s_data *data) { isl_printer *p = data->p; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "// Variable declarations"); p = isl_printer_end_line(p); p = isl_printer_print_str(p, "Var "); for (int i = 0; i < data->iter_num; i++) { char iter_str[100]; sprintf(iter_str, "c%d", i); if (i > 0) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, iter_str); } p = isl_printer_print_str(p, ";"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); return isl_stat_ok; } /* Fill up the group arrays with singleton groups, i.e., one group * per reference, initializing the array, access, write, n_ref and refs fields. * In particular the access field is initialized to the scheduled access relation * of the array references. * * Return the number of elements initialized, i.e., the number of * active references in the current kernel. */ static int t2s_populate_array_references(struct t2s_array_info *info, struct t2s_array_ref_group **groups, struct t2s_data *data) { isl_ctx *ctx = data->ctx; int n = 0; for (int i = 0; i < info->array->n_ref; i++) { isl_union_map *umap; isl_map *map; struct t2s_array_ref_group *group; struct gpu_stmt_access *access = info->array->refs[i]; map = isl_map_copy(access->access); umap = isl_union_map_from_map(map); umap = isl_union_map_apply_domain(umap, isl_union_map_copy(data->group_data->full_sched)); if (isl_union_map_is_empty(umap)) { isl_union_map_free(umap); continue; } map = isl_map_from_union_map(umap); map = isl_map_detect_equalities(map); group = isl_calloc_type(ctx, struct t2s_array_ref_group); if (!group) { isl_map_free(map); return -1; } group->t2s_array = info; group->array = info->array; group->access = map; group->write = access->write; group->exact_write = access->exact_write; group->refs = &info->array->refs[i]; group->n_ref = 1; groups[n++] = group; } return n; } static struct t2s_array_ref_group *join_groups( struct t2s_array_ref_group *group1, struct t2s_array_ref_group *group2) { isl_ctx *ctx; struct t2s_array_ref_group *group; if (!group1 || !group2) return NULL; ctx = isl_map_get_ctx(group1->access); group = isl_calloc_type(ctx, struct t2s_array_ref_group); if (!group) return NULL; group->t2s_array = group1->t2s_array; group->array = group1->array; group->access = isl_map_union(isl_map_copy(group1->access), isl_map_copy(group2->access)); group->write = group1->write || group2->write; group->exact_write = group1->exact_write && group2->exact_write; group->n_ref = group1->n_ref + group2->n_ref; group->refs = isl_alloc_array(ctx, struct gpu_stmt_access *, group->n_ref); if (!group->refs) return t2s_array_ref_group_free(group); for (int i = 0; i < group1->n_ref; i++) group->refs[i] = group1->refs[i]; for (int i = 0; i < group2->n_ref; i++) group->refs[group1->n_ref + i] = group2->refs[i]; return group; } /* Combine the given two groups into a single group and free * the original two groups. */ static struct t2s_array_ref_group *join_groups_and_free( struct t2s_array_ref_group *group1, struct t2s_array_ref_group *group2) { struct t2s_array_ref_group *group; group = join_groups(group1, group2); t2s_array_ref_group_free(group1); t2s_array_ref_group_free(group2); return group; } /* Group two writes if their live-in ranges overalp at the current iteration. */ static int t2s_group_writes(int n, struct t2s_array_ref_group **groups, int (*overlap)(struct t2s_array_ref_group *group1, struct t2s_array_ref_group *group2, void *user), struct t2s_data *data) { int i, j; int any_merge; for (i = 0; i < n; i += !any_merge) { any_merge = 0; for (j = n - 1; j > i; j--) { if (!overlap(groups[i], groups[j], data)) continue; any_merge = 1; groups[i] = join_groups_and_free(groups[i], groups[j]); if (j != n - 1) groups[j] = groups[n - 1]; groups[n - 1] = NULL; n--; if (!groups[i]) return -1; } } return n; } /* For each dependence, if the dependence distance are all zero by the members of the schedule band, * then, compute the live-range from the src to the dest of the dependence. * Otherwise, compute the live-range by not considering the dest of the dependence. */ static __isl_give isl_set *t2s_compute_dep_live_range(struct polysa_dep *d, struct t2s_data *data) { isl_basic_map *bmap; isl_basic_set *bset; isl_map *map; isl_set *set; isl_set *src_set; isl_set *dest_set; isl_map *lex_map; isl_union_map *sched; isl_set *live_range; bmap = isl_basic_map_copy(d->isl_dep); map = isl_map_factor_domain(isl_map_from_basic_map(bmap)); set = isl_map_domain(map); sched = isl_union_map_copy(data->group_data->full_sched); sched = isl_union_map_intersect_domain(sched, isl_union_set_from_set(set)); set = isl_map_range(isl_map_from_union_map(sched)); lex_map = isl_map_lex_le(isl_set_get_space(set)); for (int i = 0; i < data->iter_num; i++) { lex_map = isl_map_equate(lex_map, isl_dim_in, i, isl_dim_out, i); } src_set = isl_set_apply(set, lex_map); if (isl_vec_is_zero(d->disvec)) { bmap = isl_basic_map_copy(d->isl_dep); map = isl_map_factor_domain(isl_map_from_basic_map(bmap)); set = isl_map_range(map); sched = isl_union_map_copy(data->group_data->full_sched); sched = isl_union_map_intersect_domain(sched, isl_union_set_from_set(set)); set = isl_map_range(isl_map_from_union_map(sched)); lex_map = isl_map_lex_gt(isl_set_get_space(set)); for (int i = 0; i < data->iter_num; i++) { lex_map = isl_map_equate(lex_map, isl_dim_in, i, isl_dim_out, i); } dest_set = isl_set_apply(set, lex_map); live_range = isl_set_intersect(src_set, dest_set); } else { live_range = src_set; } return live_range; } static int accesses_overlap(struct polysa_dep *d1, struct polysa_dep *d2, int wr, struct t2s_data *data) { isl_set *live_range1; isl_set *live_range2; int r; live_range1 = t2s_compute_dep_live_range(d1, data); live_range2 = t2s_compute_dep_live_range(d2, data); if (isl_set_is_disjoint(live_range1, live_range2)) { r = 0; } else { r = 1; } isl_set_free(live_range1); isl_set_free(live_range2); return r; } /* If both accesses are write accesses with RAW dep (intermediate access), * we will check if: * 1) both writes are local to the permutable band, i.e., if they are * assigned the same value by the members of the band. * 2) if the first condition holds, check if the live-ranges (RAW) of two accesses * are overlapped. * If both conditions hold, which means that these two write accesses * need to be assigned different T2S function names to avoid overwriting * the value of each other. We will return 1 and later group them into the * same array reference group. * * If both accesses are read accesses with RAR dep (intermediate access), * we will check if: * 1) both read are local to the permutable band, i.e., if they are * assigned the same value by the members of the band. * 2) if the first condition holds, check if the live-ranges (RAR) of two accesses * are overlapped. * If both conditions hold, which means that these two read accesses * need to be assigned different T2S function names to avoid overwriting * the value of each other. We will return 1 and later group them into the * same array reference group. * * For live-out accesses (drain accesses), we will need to assign them different * function names if they are updated in the same iteration. Currently, we don't * handle this scenario as there is only one statement that involves the live-out * accesses for all of the test cases. */ static int accesses_overlap_wrap(struct t2s_array_ref_group *group1, struct t2s_array_ref_group *group2, void *user) { struct t2s_data *data = user; // // debug // isl_printer *p = isl_printer_to_file(isl_map_get_ctx(group1->access), stdout); // p = isl_printer_print_map(p, group1->access); // printf("\n"); // p = isl_printer_print_map(p, group2->access); // printf("\n"); // isl_printer_free(p); // // debug for (int i = 0; i < group1->n_ref; i++) { for (int j = 0; j < group2->n_ref; j++) { struct gpu_stmt_access *ref1 = group1->refs[i]; struct gpu_stmt_access *ref2 = group2->refs[j]; if (ref1->write == 1 && ref2->write == 1) { for (int n = 0; n < data->ndeps; n++) { struct polysa_dep *dep1 = data->deps[n]; if (dep1->type == POLYSA_DEP_RAW && dep1->src == ref1->ref_id) { for (int m = 0; m < data->ndeps; m++) { struct polysa_dep *dep2 = data->deps[m]; if (dep2->type == POLYSA_DEP_RAW && dep2->src == ref2->ref_id) { /* Examine if two write accesses are overlapped. */ return accesses_overlap(dep1, dep2, 0, data); } } } } } else if (ref1->read == 1 && ref2->read == 1) { for (int n = 0; n < data->ndeps; n++) { struct polysa_dep *dep1 = data->deps[n]; if (dep1->type == POLYSA_DEP_RAR && dep1->src == ref1->ref_id) { for (int m = 0; m < data->ndeps; m++) { struct polysa_dep *dep2 = data->deps[m]; if (dep2->type == POLYSA_DEP_RAR && dep2->src == ref2->ref_id) { /* Examine if two read accesses are overlapped. */ return accesses_overlap(dep1, dep2, 1, data); } } } } } else { return 0; } } } return 0; } static int t2s_group_overlapping_writes(int n, struct t2s_array_ref_group **groups, struct t2s_data *data) { return t2s_group_writes(n, groups, &accesses_overlap_wrap, data); } /* Set array->n_group and array->groups to n and groups. * * Additionally, set the "nr" field of each group. */ static void t2s_set_array_groups(struct t2s_array_info *array, int n, struct t2s_array_ref_group **groups) { int i; array->n_group = n; array->groups = groups; for (i = 0; i < n; i++) { groups[i]->nr = i; } } static void t2s_assign_array_group_func_id(struct t2s_data *data, struct t2s_array_info *array) { int max_n_ref = 0; int write = 0; if (data->ref2func == NULL) data->ref2func = isl_id_to_id_alloc(data->ctx, 0); if (data->func_ids == NULL) data->func_ids = isl_id_list_alloc(data->ctx, 0); for (int i = 0; i < array->n_group; i++) { struct t2s_array_ref_group *group = array->groups[i]; if (group->write == 1) write = 1; for (int r = 0; r < group->n_ref; r++) { struct gpu_stmt_access *ref = group->refs[r]; char func_name[100]; /* Fetch the array name */ isl_map *access = isl_map_copy(ref->access); isl_id *ref_id = isl_id_copy(ref->ref_id); isl_space *space = isl_map_get_space(access); const char *array_name = isl_space_get_tuple_name(space, isl_dim_out); isl_space_free(space); isl_map_free(access); if (r == 0) { sprintf(func_name, "%s", array_name); } else { sprintf(func_name, "%s_%d", array_name, r); } isl_id *func_id = isl_id_alloc(data->ctx, func_name, NULL); data->ref2func = isl_id_to_id_set(data->ref2func, ref_id, func_id); } if (group->n_ref > max_n_ref) max_n_ref = group->n_ref; } // // debug // printf("%s\n", array->array->type); // // debug /* Insert the function declaraitons. */ for (int i = 0; i < max_n_ref; i++) { char func_name[100]; if (i == 0) sprintf(func_name, "%s", array->array->name); else sprintf(func_name, "%s_%d", array->array->name, i); isl_id *func_id = isl_id_alloc(data->ctx, func_name, array->array); data->func_ids = isl_id_list_add(data->func_ids, func_id); if (write == 1) { /* Add the drain func. */ char func_name[100]; if (i == 0) sprintf(func_name, "%s_drain", array->array->name); else sprintf(func_name, "%s_%d_drain", array->array->name, i); isl_id *func_id = isl_id_alloc(data->ctx, func_name, array->array); data->func_ids = isl_id_list_add(data->func_ids, func_id); } } } static isl_stat gen_t2s_func_ids(struct t2s_data *data, struct t2s_array_info *array) { /* Populate the array groups. */ isl_ctx *ctx = data->ctx; struct t2s_array_ref_group **groups; groups = isl_calloc_array(ctx, struct t2s_array_ref_group *, array->array->n_ref); int n = t2s_populate_array_references(array, groups, data); /* Group overlapping writes. */ n = t2s_group_overlapping_writes(n, groups, data); /* Set the group information. */ t2s_set_array_groups(array, n, groups); /* Assign function names. */ t2s_assign_array_group_func_id(data, array); return isl_stat_ok; } /* Generate function declarations. * Assign a function name to each access reference. * First group references that access the same array together. * Connect all accesses in the same group together. * Inside each group, if the access is a write access (assocaited with * RAW), check if there is any other write access scheduled in-between this * write access and the read access that uses this data by RAW. * If so, break the edge between these two write accesses. * At last, compute the CCs of the graph, and assign a unique function name * to each CC of the array group. * * Inside each group, if the access is a read access (associated with * RAR), check if there is any other read access scheduled in-between this * read access and the read access that uses this data by RAR. * If so, break the edge between these two read accesses. * At last, compute the CCs of the graph, and assign a unique function name * to each CC of the array group. * * Inside each group, if the access is a write access (associated with * WAW), check if the write-out domain is empty. If not, generate a unique function * name to this write access as the drain function. */ static isl_stat gen_t2s_funcs(__isl_keep isl_schedule *schedule, struct t2s_data *data) { isl_ctx *ctx = data->ctx; isl_printer *p = data->p; struct t2s_group_data *group_data; struct gpu_prog *prog; isl_schedule_node *node; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "// Function declarations"); p = isl_printer_end_line(p); /* Initialization. */ prog = gpu_prog_alloc(ctx, data->scop); group_data = isl_calloc_type(ctx, struct t2s_group_data); data->array = isl_calloc_array(ctx, struct t2s_array_info, prog->n_array); data->n_array = prog->n_array; for (int i = 0; i < prog->n_array; i++) { data->array[i].array = &prog->array[i]; } node = isl_schedule_get_root(schedule); group_data->full_sched = isl_schedule_node_get_subtree_schedule_union_map(node); isl_schedule_node_free(node); data->group_data = group_data; for (int i = 0; i < data->n_array; i++) { gen_t2s_func_ids(data, &data->array[i]); } // // debug // isl_printer *p_debug = isl_printer_to_file(data->ctx, stdout); // p_debug = isl_printer_print_id_to_id(p_debug, data->ref2func); // printf("\n"); // isl_printer_free(p_debug); // // debug data->group_data = t2s_group_data_free(group_data); /* Print the function decls. */ for (int i = 0; i < isl_id_list_n_id(data->func_ids); i++) { isl_id *func_id = isl_id_list_get_id(data->func_ids, i); struct gpu_array_info *array = isl_id_get_user(func_id); p = isl_printer_start_line(p); p = isl_printer_print_str(p, "#define FUNC_S"); p = isl_printer_print_int(p, i); p = isl_printer_print_str(p, " type_of<"); p = isl_printer_print_str(p, array->type); p = isl_printer_print_str(p, ">(), {"); for (int j = 0; j < data->iter_num; j++) { if (j > 0) p = isl_printer_print_str(p, ", "); p = isl_printer_print_str(p, "c"); p = isl_printer_print_int(p, j); } p = isl_printer_print_str(p, "}, Place::Host"); p = isl_printer_end_line(p); isl_id_free(func_id); } p = isl_printer_start_line(p); p = isl_printer_print_str(p, "Func "); for (int i = 0; i < isl_id_list_n_id(data->func_ids); i++) { isl_id *func_id = isl_id_list_get_id(data->func_ids, i); if (i > 0) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, isl_id_get_name(func_id)); p = isl_printer_print_str(p, "(FUNC_S"); p = isl_printer_print_int(p, i); p = isl_printer_print_str(p, ")"); isl_id_free(func_id); } p = isl_printer_print_str(p, ";"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_end_line(p); gpu_prog_free(prog); return isl_stat_ok; } /* Generate T2S space-time transformation. */ static isl_stat gen_t2s_space_time(struct t2s_data *data) { struct t2s_URE *d_URE; isl_printer *p = data->p; p = isl_printer_start_line(p); p = isl_printer_print_str(p, "// Space-time transformation"); p = isl_printer_end_line(p); /* Define time and space loop variables. */ p = isl_printer_start_line(p); p = isl_printer_print_str(p, "Var "); int is_var_first = 1; for (int i = 0; i < data->prog->time_w; i++) { if (!is_var_first) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, "tloop"); p = isl_printer_print_int(p, i); if (is_var_first) { is_var_first = 0; } } for (int i = 0; i < data->prog->space_w; i++) { if (!is_var_first) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, "sloop"); p = isl_printer_print_int(p, i); if (is_var_first) { is_var_first = 0; } } p = isl_printer_print_str(p, ";"); p = isl_printer_end_line(p); for (int i = 0; i < data->URE_num; i++) { if (data->URE[i]->d == 1) { d_URE = data->URE[i]; if (d_URE->update_level == -1) break; } } assert(d_URE->update_level == -1); p = isl_printer_start_line(p); p = isl_printer_print_str(p, d_URE->name); p = isl_printer_print_str(p, "."); p = isl_printer_print_str(p, "merge_defs("); p = isl_printer_print_str(p, "{"); int is_first = 1; for (int i = 0; i < data->URE_num; i++) { struct t2s_URE *URE = data->URE[i]; if (URE->update_level >= 0) { if (!is_first) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, URE->name); if (is_first) is_first = 0; } } p = isl_printer_print_str(p, "}, {"); is_first = 1; for (int i = 0; i < data->URE_num; i++) { struct t2s_URE *URE = data->URE[i]; if (URE->update_level == -1 && URE->d == 0) { if (!is_first) { p = isl_printer_print_str(p, ", "); } p = isl_printer_print_str(p, URE->name); if (is_first) is_first = 0; } } p = isl_printer_print_str(p, "}"); p = isl_printer_print_str(p, ")"); p = isl_printer_end_line(p); p = isl_printer_indent(p, strlen(d_URE->name)); p = isl_printer_start_line(p); p = isl_printer_print_str(p, ".reorder_inward("); is_first = 1; for (int i = 0; i < data->iter_num; i++) { if (!is_first) p = isl_printer_print_str(p, ", "); char iter_name[100]; sprintf(iter_name, "c%d", i); p = isl_printer_print_str(p, iter_name); if (is_first) is_first = 0; } p = isl_printer_print_str(p, ")"); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_print_str(p, ".space_time_transform("); // TODO int indent = strlen(".space_time_transform("); p = isl_printer_indent(p, indent); p = isl_printer_print_str(p, "{"); for (int i = 0; i < data->iter_num; i++) { if (i > 0) p = isl_printer_print_str(p, ", "); char iter_name[100]; sprintf(iter_name, "c%d", i); p = isl_printer_print_str(p, iter_name); } p = isl_printer_print_str(p, "},"); p = isl_printer_end_line(p); /* Space and time loops. */ isl_printer *p_str = isl_printer_to_str(data->ctx); p_str = isl_printer_print_str(p_str, "{"); for (int i = 0; i < data->prog->time_w; i++) { if (i > 0) p_str = isl_printer_print_str(p_str, ", "); p_str = isl_printer_print_str(p_str, "tloop"); p_str = isl_printer_print_int(p_str, i); } p_str = isl_printer_print_str(p_str, "}"); char *tloop_list = isl_printer_get_str(p_str); isl_printer_free(p_str); p_str = isl_printer_to_str(data->ctx); p_str = isl_printer_print_str(p_str, "{"); for (int i = 0; i < data->prog->space_w; i++) { if (i > 0) p_str = isl_printer_print_str(p_str, ", "); p_str = isl_printer_print_str(p_str, "sloop"); p_str = isl_printer_print_int(p_str, i); } p_str = isl_printer_print_str(p_str, "}"); char *sloop_list = isl_printer_get_str(p_str); isl_printer_free(p_str); if (data->prog->type == POLYSA_SA_TYPE_ASYNC) { p = isl_printer_start_line(p); p = isl_printer_print_str(p, sloop_list); p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_print_str(p, tloop_list); p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } else if (data->prog->type == POLYSA_SA_TYPE_SYNC) { p = isl_printer_start_line(p); p = isl_printer_print_str(p, tloop_list); p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); p = isl_printer_start_line(p); p = isl_printer_print_str(p, sloop_list); p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } free(tloop_list); free(sloop_list); /* Transform matrix. */ for (int i = 0; i < data->iter_num; i++) { p = isl_printer_start_line(p); if (i == 0) { p = isl_printer_print_str(p, "{"); p = isl_printer_indent(p, 1); } for (int j = 0; j < data->iter_num; j++) { if (j > 0) p = isl_printer_print_str(p, ", "); if (i == j) p = isl_printer_print_int(p, 1); else p = isl_printer_print_int(p, 0); } if (i == data->iter_num - 1) { p = isl_printer_print_str(p, "}"); p = isl_printer_indent(p, -1); } p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } /* Reverse transform matrix. */ for (int i = 0; i < data->iter_num; i++) { p = isl_printer_start_line(p); if (i == 0) { p = isl_printer_print_str(p, "{"); p = isl_printer_indent(p, 1); } for (int j = 0; j < data->iter_num; j++) { if (j > 0) p = isl_printer_print_str(p, ", "); if (i == j) p = isl_printer_print_int(p, 1); else p = isl_printer_print_int(p, 0); } if (i == data->iter_num - 1) { p = isl_printer_print_str(p, "}"); p = isl_printer_indent(p, -1); } if (i == data->iter_num - 1) p = isl_printer_print_str(p, ")"); else p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } p = isl_printer_indent(p, -indent); p = isl_printer_start_line(p); p = isl_printer_print_str(p, ".domain("); int indent_tmp = strlen(".domain("); p = isl_printer_indent(p, indent_tmp); for (int i = 0; i < data->iter_num; i++) { if (i > 0) p = isl_printer_start_line(p); struct polysa_iter *iter = data->iter[i]; p = isl_printer_print_str(p, iter->name); p = isl_printer_print_str(p, ", "); p = isl_printer_set_output_format(p, ISL_FORMAT_C); p = isl_printer_print_aff(p, iter->lb); p = isl_printer_print_str(p, ", "); p = isl_printer_print_aff(p, iter->ub); p = isl_printer_print_str(p, ", "); p = isl_printer_print_int(p, iter->stride); p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } /* Add time and space loops. */ for (int i = 0; i < data->iter_num; i++) { p = isl_printer_start_line(p); struct polysa_iter *iter = data->iter[i]; p = isl_printer_print_str(p, iter->ts_name); p = isl_printer_print_str(p, ", "); p = isl_printer_set_output_format(p, ISL_FORMAT_C); p = isl_printer_print_aff(p, iter->lb); p = isl_printer_print_str(p, ", "); p = isl_printer_print_aff(p, iter->ub); p = isl_printer_print_str(p, ", "); p = isl_printer_print_int(p, iter->stride); if (i == data->iter_num - 1) p = isl_printer_print_str(p, ");"); else p = isl_printer_print_str(p, ","); p = isl_printer_end_line(p); } p = isl_printer_indent(p, -indent_tmp); p = isl_printer_set_output_format(p, ISL_FORMAT_ISL); p = isl_printer_indent(p, -strlen(d_URE->name)); p = isl_printer_start_line(p); p = isl_printer_end_line(p); return isl_stat_ok; } static __isl_give struct t2s_data *t2s_data_init(__isl_take struct t2s_data *d) { d->anchor_domain = NULL; d->stmt_domain = NULL; d->stmt_sim_domain = NULL; d->URE = NULL; d->URE_num = 0; d->t2s_stmt_num = 0; d->t2s_stmt_text = NULL; d->iter_num = 0; d->iter = NULL; d->scop = NULL; d->p = NULL; d->ctx = NULL; d->deps = NULL; d->ndeps = 0; d->ref2func = NULL; // d->ref2dfunc = NULL; d->func_ids = NULL; d->stmt_data = NULL; d->n_array = 0; d->array = NULL; d->group_data = NULL; d->prog = NULL; d->schedule = NULL; } static isl_stat extract_anchor_domain(__isl_keep isl_schedule *schedule, struct t2s_data *data) { isl_schedule_node *root = isl_schedule_get_root(schedule); isl_union_set *domain = isl_schedule_get_domain(schedule); isl_union_map *sched = isl_schedule_node_get_subtree_schedule_union_map(root); isl_schedule_node_free(root); isl_union_set *anchor_domain = isl_union_set_apply(domain, sched); // // debug // isl_printer *p = isl_printer_to_file(isl_union_set_get_ctx(anchor_domain), stdout); // p = isl_printer_print_union_set(p, anchor_domain); // printf("\n"); // // debug data->anchor_domain = isl_set_from_union_set(anchor_domain); return isl_stat_ok; } /* Generate T2S code from schedule. */ static isl_stat print_t2s_with_schedule( __isl_keep struct polysa_prog *prog, __isl_keep struct ppcg_scop *scop) { struct t2s_data *data; isl_union_set *stmt_domains; isl_union_map *stmt_schedules; isl_schedule_node *node; isl_union_set *stmt_trans_domains; isl_space *stmt_space; isl_ctx *ctx; isl_schedule *schedule; int t2s_tile_second_phase; schedule = prog->schedule; ctx = isl_schedule_get_ctx(schedule); data = isl_calloc_type(ctx, struct t2s_data); data = t2s_data_init(data); t2s_tile_second_phase = (scop->options->t2s_tile && scop->options->t2s_tile_phase == 1); data->ctx = ctx; data->scop = scop; data->prog = prog; data->schedule = schedule; FILE *t2s_fp = fopen("t2s.cpp", "w"); data->p = isl_printer_to_file(ctx, t2s_fp); /* Print out the headers. */ gen_t2s_headers(data); data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "int main(void) {"); data->p = isl_printer_end_line(data->p); /* Calcualte the iterator num. */ data->iter_num = 0; isl_schedule_foreach_schedule_node_top_down(schedule, &update_depth, &data->iter_num); /* Update the deps. */ data->ndeps = 0; data->deps = NULL; schedule = extract_deps(schedule, data); /* Calculate the anchor domain. * Allocate a empty set then unionize it with the scheduling domain of each statement. */ data->anchor_domain = NULL; extract_anchor_domain(schedule, data); /* Generate the iterator meta data. */ extract_iters(schedule, data); /* Calculate the simplified domain (in scheduling dims) for each statement. */ data->stmt_domain = NULL; data->stmt_sim_domain = NULL; extract_stmt_domain(schedule, data); /* Generate input declarations. */ gen_t2s_inputs(data); /* Generate variable declarations. */ gen_t2s_vars(data); /* Generate function declarations. */ gen_t2s_funcs(schedule, data); /* Generate the T2S statements .*/ data->t2s_stmt_num = 0; data->t2s_stmt_text = NULL; schedule = gen_stmt_text_wrap(schedule, data); /* Generate time-space transformation. */ if (!t2s_tile_second_phase) { gen_t2s_space_time(data); } else { data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "// Space-time transformation (Fill in manually)"); data->p = isl_printer_end_line(data->p); data->p = isl_printer_start_line(data->p); data->p = isl_printer_end_line(data->p); } data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "// PE optimization (Fill in manually)"); data->p = isl_printer_end_line(data->p); data->p = isl_printer_start_line(data->p); data->p = isl_printer_end_line(data->p); data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "// CPU verification (Fill in manually)"); data->p = isl_printer_end_line(data->p); data->p = isl_printer_start_line(data->p); data->p = isl_printer_end_line(data->p); data->p = isl_printer_start_line(data->p); data->p = isl_printer_print_str(data->p, "}"); data->p = isl_printer_end_line(data->p); fclose(t2s_fp); t2s_data_free(data); prog->schedule = schedule; return isl_stat_ok; } static isl_bool no_band_node_as_descendant(__isl_keep isl_schedule_node *node, void *user){ enum isl_schedule_node_type node_type = isl_schedule_node_get_type(node); if (node_type == isl_schedule_node_band) { return isl_bool_false; } else { return isl_bool_true; } } /* No band node is allowed after the sequence or set node. */ static isl_bool t2s_legal_at_node(__isl_keep isl_schedule_node *node, void *user) { enum isl_schedule_node_type node_type = isl_schedule_node_get_type(node); if (node_type == isl_schedule_node_sequence || node_type == isl_schedule_node_set) { int n_node_has_band = 0; for (int n = 0; n < isl_schedule_node_n_children(node); n++) { node = isl_schedule_node_child(node, n); isl_bool no_band = isl_schedule_node_every_descendant(node, &no_band_node_as_descendant, NULL); if (!no_band) n_node_has_band++; } if (n_node_has_band > 2) { return isl_bool_false; } else { return isl_bool_true; } } else { return isl_bool_true; } } /* Check if there is only nested permuted band in the program. */ static isl_bool t2s_legality_check(__isl_keep isl_schedule *schedule) { isl_schedule_node *root = isl_schedule_get_root(schedule); isl_bool is_legal = isl_schedule_node_every_descendant(root, &t2s_legal_at_node, NULL); isl_schedule_node_free(root); return is_legal; } /* Generate CPU code for "scop" and print it to "p". * * First obtain a schedule for "scop" and then print code for "scop" * using that schedule. * * To generate T2S code from the tiled design, there are two phases. * In the first phase, a tiled CPU program is generated w/o T2S program. * In the second phase, the tiled CPU program is taken in and the T2S program * with tiled UREs are generated. */ static __isl_give isl_printer *generate(__isl_take isl_printer *p, struct ppcg_scop *scop, struct ppcg_options *options) { isl_schedule *schedule; int t2s_tile_second_phase = (options->t2s_tile && options->t2s_tile_phase == 1); int t2s_tile_first_phase = (options->t2s_tile && options->t2s_tile_phase == 0); if (t2s_tile_second_phase) { /* In the second phase, the reschedule is disabled so that the * original schedule from the program is used. */ options->reschedule = 0; } schedule = get_schedule(scop, options); // // debug // isl_printer *p_debug = isl_printer_to_file(isl_schedule_get_ctx(schedule), stdout); // p_debug = isl_printer_set_yaml_style(p_debug, ISL_YAML_STYLE_BLOCK); // p_debug = isl_printer_print_schedule(p_debug, schedule); // printf("\n"); // p_debug = isl_printer_print_union_map(p_debug, scop->tagged_dep_flow); // printf("\n"); // p_debug = isl_printer_print_union_map(p_debug, scop->tagged_dep_waw); // printf("\n"); // p_debug = isl_printer_print_union_map(p_debug, scop->tagged_dep_rar); // printf("\n"); // isl_printer_free(p_debug); // // debug if (!t2s_tile_second_phase) { /* Check if the program is legal to be mapped to systolic array. */ isl_bool is_legal = sa_legality_check(schedule, scop); if (is_legal != isl_bool_true) { printf("[PolySA] Illegal to be transformed to systolic array.\n"); } if (is_legal) { /* Generate systolic arrays using space-time mapping. */ isl_size num_sa = 0; struct polysa_prog **sa_candidates = sa_space_time_transform(schedule, scop, &num_sa); if (num_sa > 0) { printf("[PolySA] %d systolic arrays generated.\n", num_sa); } // TODO: All the SA candidates keep the same schedule tree. We need to duplicate them to // seperate the transformation performed on each array. /* Pick up one systolic array to preceed based on heuristics. */ struct polysa_prog *sa_opt = sa_candidates_smart_pick(sa_candidates, num_sa); if (t2s_tile_first_phase) { /* Apply PE optimization. */ sa_pe_optimize(sa_opt); } // // debug // // isl_printer *p = isl_printer_to_file(isl_schedule_get_ctx(sa_opt->schedule), stdout); // p_debug = isl_printer_print_schedule(p_debug, sa_opt->schedule); // printf("\n"); // // debug if (!t2s_tile_first_phase) { /* Generate T2S program. */ isl_bool is_t2s_legal = t2s_legality_check(sa_opt->schedule); if (is_t2s_legal) { print_t2s_with_schedule(sa_opt, scop); } else { printf("[PolySA] Illegal to be transformed to T2S program.\n"); } } schedule = isl_schedule_copy(sa_opt->schedule); polysa_prog_free(sa_opt); } } else { struct polysa_prog *sa = polysa_prog_from_schedule(schedule); sa->scop = scop; // TODO: sa->type // TODO: sa->array_dim // TODO: sa->array_part_w // TODO: sa->space_w // TODO: sa->time_w print_t2s_with_schedule(sa, scop); schedule = isl_schedule_copy(sa->schedule); polysa_prog_free(sa); } /* Generate the transformed CPU program. */ return print_cpu_with_schedule(p, scop, schedule, options); } /* Wrapper around generate for use as a ppcg_transform callback. */ static __isl_give isl_printer *print_polysa_t2s_wrap(__isl_take isl_printer *p, struct ppcg_scop *scop, void *user) { struct ppcg_options *options = user; return generate(p, scop, options); } /* Transform the code in the file called "input" by replacing * all scops by corresponding CPU code and write the results to a file * called "output". */ int generate_polysa_t2s(isl_ctx *ctx, struct ppcg_options *options, const char *input, const char *output) { FILE *output_file; int r; /* Return the handle of the output file. */ output_file = get_output_file(input, output); if (!output_file) return -1; /* Extract each scop from the program and call the callback * function to process it. */ r = ppcg_transform(ctx, input, output_file, options, &print_polysa_t2s_wrap, options); fclose(output_file); return r; }
bug3.c
/****************************************************************************** * FILE: omp_bug3.c * DESCRIPTION: * Run time error * AUTHOR: Blaise Barney 01/09/04 * LAST REVISED: 06/28/05 ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #define N 50 int main (int argc, char *argv[]) { int i, nthreads, tid, section; float a[N], b[N], c[N]; void print_results(float array[N], int tid, int section); /* Some initializations */ for (i=0; i<N; i++) a[i] = b[i] = i * 1.0; #pragma omp parallel private(c,i,tid,section) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } /*** Use barriers for clean output ***/ #pragma omp barrier printf("Thread %d starting...\n",tid); #pragma omp barrier #pragma omp sections nowait { #pragma omp section { section = 1; for (i=0; i<N; i++) c[i] = a[i] * b[i]; print_results(c, tid, section); } #pragma omp section { section = 2; for (i=0; i<N; i++) c[i] = a[i] + b[i]; print_results(c, tid, section); } } /* end of sections */ /*** Use barrier for clean output ***/ #pragma omp barrier printf("Thread %d exiting...\n",tid); } /* end of parallel section */ } void print_results(float array[N], int tid, int section) { int i,j; j = 1; /*** use critical for clean output ***/ #pragma omp critical { printf("\nThread %d did section %d. The results are:\n", tid, section); for (i=0; i<N; i++) { printf("%e ",array[i]); j++; if (j == 6) { printf("\n"); j = 1; } } printf("\n"); } /*** end of critical ***/ // #pragma omp barrier printf("Thread %d done and synchronized.\n", tid); }
GB_binop__div_uint8.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__div_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__div_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__div_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__div_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__div_uint8) // A*D function (colscale): GB (_AxD__div_uint8) // D*A function (rowscale): GB (_DxB__div_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__div_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__div_uint8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__div_uint8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__div_uint8) // C=scalar+B GB (_bind1st__div_uint8) // C=scalar+B' GB (_bind1st_tran__div_uint8) // C=A+scalar GB (_bind2nd__div_uint8) // C=A'+scalar GB (_bind2nd_tran__div_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_IDIV_UNSIGNED (aij, bij, 8) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IDIV_UNSIGNED (x, y, 8) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_DIV || GxB_NO_UINT8 || GxB_NO_DIV_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__div_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__div_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__div_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__div_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__div_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__div_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__div_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__div_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__div_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__div_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__div_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__div_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (x, bij, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__div_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (aij, y, 8) ; } 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) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (x, aij, 8) ; \ } GrB_Info GB (_bind1st_tran__div_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // 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) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, y, 8) ; \ } GrB_Info GB (_bind2nd_tran__div_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
8078.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 target teams distribute for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp parallel for simd num_threads(8) 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; }
omptests.c
#include <stdlib.h> #include <stdio.h> #pragma omp requires unified_shared_memory /// Two methods store in different compilation units, results in a compile-time // error. Duplicate .omp_offloading.entry void test_comp_unit_1(const int niters, double* a); void test_comp_unit_2(const int niters, double* a); int main() { const int niters = 10; double* a = (double*)malloc(sizeof(double)*niters); #pragma omp target data map(from:a[:niters]) { test_comp_unit_1(niters, a); test_comp_unit_2(niters, a); } double res = 0.0; for(int ii = 0; ii < niters; ++ii) { res += a[ii]; } printf("--> %s <--\n",(res < 90.001 && res > 89.999) ? "success" : "error"); return 0; } /// Presumably creates an .omp_offloading.entry void test_comp_unit_1(const int niters, double* a) { #pragma omp target for(int ii = 0; ii < niters; ++ii) a[ii] = (double)ii; }
gpufont_ttf_file.c
#include <stdlib.h> #include <stdio.h> #include <netinet/in.h> /* ntohl */ #include <string.h> /* memset */ #include <stdio.h> #include "gpufont_data.h" #include "gpufont_ttf_file.h" #include "ttf_defs.h" #include "triangulate.h" #pragma pack(1) typedef int8_t int8; typedef int16_t int16; typedef int32_t int32; typedef uint8_t uint8; typedef uint16_t uint16; typedef uint32_t uint32; typedef unsigned uint; enum { DEBUG_DUMP = 0, /* enable/disable level 1 debug messages */ DEBUG_DUMP2 = 0, /* enable/disable level 2 debug messages */ ENABLE_OPENMP = 1 /* used for triangulating glyphs. huge speed boost for CJK fonts */ }; /* todo: - metrics - support more cmap formats - proper TTC support */ static int read_shorts( FILE *fp, uint16 x[], uint32 count ) { uint32 n; if ( fread( x, 2, count, fp ) != count ) return 1; for( n=0; n<count; n++ ) x[n] = ntohs( x[n] ); return 0; } #if ENABLE_COMPOSITE_GLYPHS /* Used by read_glyph */ static void *read_composite_glyph( FILE *fp, float units_per_em, Font font[1], FontStatus status[1] ) { /* SubGlyphHeader */ struct { uint16 flags, glyph_index; } sgh; uint16 num = 0; /* temporary counter used to indicate the index of current subglyph in the CompositeGlyph */ void *glyph_data = NULL; /* points to a CompositeGlyph, whose size is not yet known */ /* num_subglyphs begins as zero because of calloc */ glyph_data = calloc( 1, sizeof(size_t) ); if ( !glyph_data ) { *status = F_FAIL_ALLOC; return NULL; } do { int16 args[2]; /* These pointers alias glyph_data */ size_t *num_subglyphs; GlyphIndex *sg_indices; float *sg_matrix; float *sg_offset; int16 fixed_matrix[4]; int e; num_subglyphs = glyph_data; *num_subglyphs += 1; glyph_data = realloc( glyph_data, COMPOSITE_GLYPH_SIZE( *num_subglyphs ) ); if ( !glyph_data ) { *status = F_FAIL_ALLOC; return NULL; } num_subglyphs = glyph_data; sg_indices = (GlyphIndex*)( num_subglyphs + 1 ); sg_matrix = (float*)( sg_indices + *num_subglyphs ) + num * 6; sg_offset = sg_matrix + 4; if ( read_shorts( fp, &sgh.flags, 2 ) ) { *status = F_FAIL_EOF; goto error_handler; } if ( sgh.glyph_index >= font->num_glyphs ) sgh.glyph_index = 0; sg_indices[ num ] = sgh.glyph_index; if ( sgh.flags & COM_ARGS_ARE_WORDS ) { /* 16-bit args */ if ( read_shorts( fp, (uint16*) args, 2 ) ) { *status = F_FAIL_EOF; goto error_handler; } } else { /* 8-bit args */ int8 temp[2]; if ( fread( temp, 1, 2, fp ) != 2 ) { *status = F_FAIL_EOF; goto error_handler; } args[0] = temp[0]; args[1] = temp[1]; } sg_offset[0] = 0; sg_offset[1] = 0; if ( sgh.flags & COM_ARGS_ARE_XY_VALUES ) { /* args are an offset vector */ sg_offset[0] = args[0] / units_per_em; sg_offset[1] = args[1] / units_per_em; } else { /* args are point indices todo: 1. find the GlyphTriangles that corresponds to glyph_index 2. get coordinates of the relevant points Either arg1 or arg2 is presumably a point index of the subglyph. But the composite glyph has no points of it's own, so what does the other argument refer to??? */ (void) font; printf( "todo: match points\n" ); } fixed_matrix[0] = 1; fixed_matrix[1] = 0; fixed_matrix[2] = 0; fixed_matrix[3] = 1; /* FreeType has "else" between these 3 ifs But what if all 3 bits are set? */ if ( sgh.flags & COM_HAVE_A_SCALE ) { if ( read_shorts( fp, (uint16*) fixed_matrix, 1 ) ) { *status = F_FAIL_EOF; goto error_handler; } fixed_matrix[3] = fixed_matrix[0]; } else if ( sgh.flags & COM_HAVE_X_AND_Y_SCALE ) { int16 temp[2]; if ( read_shorts( fp, (uint16*) temp, 2 ) ) { *status = F_FAIL_EOF; goto error_handler; } fixed_matrix[0] = temp[0]; fixed_matrix[3] = temp[1]; } else if ( sgh.flags & COM_HAVE_MATRIX ) { if ( read_shorts( fp, (uint16*) fixed_matrix, 4 ) ) { *status = F_FAIL_EOF; goto error_handler; } } for( e=0; e<4; e++ ) sg_matrix[e] = fixed_matrix[e] / (float) ( 1 << 14 ); num++; } while( sgh.flags & 0x20 ); *status = F_SUCCESS; return glyph_data; error_handler:; if ( glyph_data ) free( glyph_data ); return NULL; } #endif static int read_contour_coord( FILE *fp, PointFlag flags, int32 co[1] ) { uint8 is_short = flags & PT_SHORT_X; uint8 is_same = flags & PT_SAME_X; if ( is_short ) { /* is_same is now the sign; 0x10=positive, 0x00=negative */ uint8 delta; if ( fread( &delta, 1, 1, fp ) != 1 ) return 0; if ( is_same ) *co += delta; else *co -= delta; } else { /* Use the previous coordinate if same_bit is set Otherwise, read a 16-bit delta value */ if ( !is_same ) { int16 delta; if ( read_shorts( fp, (uint16*) &delta, 1 ) ) return 0; *co += delta; } } return 1; } /* Used by read_glyph */ static SimpleGlyph *read_simple_glyph( FILE *fp, uint16 num_contours, FontStatus status[1] ) { SimpleGlyph *glyph = NULL; uint16 *end_points = NULL; PointCoord *final_points = NULL; uint32 num_points; uint32 n; int32 prev_coord; PointFlag *final_flags = NULL; uint16 num_instr; if ( DEBUG_DUMP2 ) { printf( "Reading contour data...\n" ); } end_points = calloc( num_contours, 2 ); if ( !end_points ) { *status = F_FAIL_ALLOC; return NULL; } if ( read_shorts( fp, end_points, num_contours ) ) { *status = F_FAIL_EOF; goto error_handler; } num_points = end_points[ num_contours - 1 ] + 1; if ( num_points > MAX_GLYPH_POINTS ) { if ( DEBUG_DUMP ) { printf( "MAX_GLYPH_POINTS too small (need %u)\n", (uint) num_points ); } *status = F_FAIL_BUFFER_LIMIT; goto error_handler; } final_flags = malloc( MAX_GLYPH_POINTS * sizeof( PointFlag ) ); final_points = malloc( MAX_GLYPH_POINTS * sizeof( PointCoord ) * 2 ); if ( !final_points || !final_flags ) { *status = F_FAIL_ALLOC; goto error_handler; } /* Skip the hinting instruction */ if ( read_shorts( fp, &num_instr, 1 ) ) { *status = F_FAIL_EOF; goto error_handler; } if ( fseek( fp, num_instr, SEEK_CUR ) < 0 ) { *status = F_FAIL_CORRUPT; goto error_handler; } /* Determine the size of X coordinate array by scanning the flags */ n = 0; while( n < num_points ) { uint32 end, count=1; uint8 flags; if ( fread( &flags, 1, 1, fp ) != 1 ) { *status = F_FAIL_EOF; goto error_handler; } if ( flags & PT_SAME_FLAGS ) { uint8 repeat; if ( fread( &repeat, 1, 1, fp ) != 1 ) { *status = F_FAIL_EOF; goto error_handler; } count += repeat; } end = n + count; if ( end > num_points ) { /* more flags than points */ *status = F_FAIL_CORRUPT; goto error_handler; } while( n < end ) final_flags[n++] = flags; } if ( n != num_points ) { /* less flags than points */ *status = F_FAIL_CORRUPT; goto error_handler; } /* Read coordinates. First X, then Y */ *status = F_FAIL_EOF; for( prev_coord=n=0; n<num_points; n++ ) { int32 x = prev_coord; if ( !read_contour_coord( fp, final_flags[n], &x ) ) goto error_handler; final_points[2*n] = prev_coord = x; } for( prev_coord=n=0; n<num_points; n++ ) { int32 y = prev_coord; if ( !read_contour_coord( fp, final_flags[n]>>1, &y ) ) goto error_handler; final_points[2*n+1] = prev_coord = y; final_flags[n] &= PT_ON_CURVE; /* discard all flags except the one that matters */ } glyph = calloc( 1, sizeof( SimpleGlyph ) ); /* calloc sets glyph->num_parts to 0, which very is important because that zero tells the glyph is not a composite glyph */ if ( !glyph ) { *status = F_FAIL_ALLOC; } else { glyph->tris.num_points_orig = num_points; glyph->tris.end_points = end_points; glyph->tris.points = final_points; glyph->tris.flags = final_flags; glyph->tris.num_contours = num_contours; /* these three must not be free'd since they are in use: */ end_points = NULL; final_points = NULL; final_flags = NULL; if ( DEBUG_DUMP2 ) printf( "Glyph read succesfully\n" ); *status = F_SUCCESS; } error_handler:; if ( final_points ) free( final_points ); if ( final_flags ) free( final_flags ); if ( end_points ) free( end_points ); return glyph; } static FontStatus read_glyph( FILE *fp, Font font[1], uint32 glyph_index, uint32 glyph_file_pos, unsigned glyph_counts[2] ) { /* GlyphHeader */ struct { uint16 num_contours; int16 xmin, ymin, xmax, ymax; } header; FontStatus status = F_FAIL_IMPOSSIBLE; if ( fseek( fp, glyph_file_pos, SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; if ( read_shorts( fp, &header.num_contours, 5 ) ) return F_FAIL_EOF; if ( header.num_contours >= 0x1000 ) { #if ENABLE_COMPOSITE_GLYPHS font->glyphs[ glyph_index ] = read_composite_glyph( fp, units_per_em, font, &status ); glyph_counts[1] += ( status == F_SUCCESS ); if ( DEBUG_DUMP2 && font->glyphs[ glyph_index ] ) { printf( "Glyph %u is a composite glyph. Has %u components\n", (uint) glyph_index, (uint) font->glyphs[ glyph_index ]->num_parts ); } #else status = F_SUCCESS; #endif } else { font->glyphs[ glyph_index ] = read_simple_glyph( fp, header.num_contours, &status ); glyph_counts[0] += ( status == F_SUCCESS ); } return status; } /* Reads both 'loca' and 'glyf' tables */ static FontStatus read_all_glyphs( FILE *fp, Font font[1], int16 format, uint32 glyph_base_offset ) { void *loca_p; uint32 n = 0; FontStatus status; unsigned glyph_counts[2] = {0,0}; if ( DEBUG_DUMP ) printf( "loca format %u (%s)\n", format, format ? "32-bit" : "16-bit" ); if ( format == 0 ) { /* 16-bit glyph location table */ uint16 *loca, prev_loc; loca = loca_p = calloc( font->num_glyphs, 2 ); if ( !loca ) return F_FAIL_ALLOC; if ( read_shorts( fp, loca, font->num_glyphs ) ) status = F_FAIL_EOF; else { prev_loc = loca[1]; status = F_FAIL_INCOMPLETE; for( n=0; n<font->num_glyphs; n++ ) { uint32 loc = loca[n]; if ( loc == prev_loc ) { /* This glyph has no outline and can be left as NULL */ continue; } if ( DEBUG_DUMP2 ) printf( "Reading glyph %u out of %u\n", (uint) n, (uint) font->num_glyphs ); prev_loc = loc; status = read_glyph( fp, font, n, (uint32) loc * 2 + glyph_base_offset, glyph_counts ); if ( status != F_SUCCESS ) break; } } } else { /* 32-bit glyph location table */ uint32 *loca, prev_loc; loca = loca_p = calloc( font->num_glyphs, 4 ); if ( !loca ) return F_FAIL_ALLOC; if ( fread( loca, 4, font->num_glyphs, fp ) != font->num_glyphs ) { status = F_FAIL_EOF; } else { prev_loc = loca[1]; status = F_FAIL_INCOMPLETE; for( n=0; n<font->num_glyphs; n++ ) { if ( loca[n] == prev_loc ) continue; if ( DEBUG_DUMP2 ) printf( "Reading glyph %u out of %u\n", (uint) n, (uint) font->num_glyphs ); prev_loc = loca[n]; status = read_glyph( fp, font, n, ntohl( loca[n] ) + glyph_base_offset, glyph_counts ); if ( status != F_SUCCESS ) break; } } } if ( DEBUG_DUMP ) { printf( "Read %u out of %u glyphs\n" "Simple glyphs: %u\n" "Composite glyphs: %u\n", (uint) n, (uint) font->num_glyphs, glyph_counts[0], glyph_counts[1] ); } free( loca_p ); return status; } static FontStatus read_cmap_format4( FILE *fp, Font font[1], uint32 total_length ) { uint16 *whole_table; uint16 *end_codes, *start_codes, *id_range_offset; int16 *id_delta; uint16 seg_count, s; uint32 max_k; unsigned total_indices = 0; unsigned n_valid = 0; /* because format and length have been already read */ total_length -= 2*2; if ( ( whole_table = malloc( total_length ) ) == NULL ) return F_FAIL_ALLOC; if ( read_shorts( fp, whole_table, total_length >> 1 ) ) return F_FAIL_EOF; seg_count = whole_table[1] >> 1; end_codes = whole_table + 5; start_codes = end_codes + seg_count + 1; id_delta = (int16*) start_codes + seg_count; id_range_offset = start_codes + 2 * seg_count; max_k = total_length / 2 - ( id_range_offset - whole_table ); if ( DEBUG_DUMP ) printf( "Segments: %u\nmax_k=%u\n", (uint) seg_count, (uint) max_k ); for( s=0; s<seg_count; s++ ) { uint16 c, start, end, stop; uint16 idro; int16 idde; end = end_codes[s]; start = start_codes[s]; idro = id_range_offset[s]; idde = id_delta[s]; stop = end + 1; total_indices += end - start + 1; /* printf( "start %u end %u idro %u idde %u\n", start, end, idro, idde ); */ if ( start > end ) { free( whole_table ); return F_FAIL_CORRUPT; } if ( idro != 0 ) { /* glyphIndex = *( &idRangeOffset[i] + idRangeOffset[i] / 2 + (c - startCode[i]) ) a <= c <= b glyphIndex = *( &idRangeOffset[i] + idRangeOffset[i] / 2 + (c - startCode[i]) ) glyphIndex = *( &idRangeOffset[i] + idRangeOffset[i] / 2 + c - startCode[i] ) glyphIndex = *( idRangeOffset + i + idRangeOffset[i] / 2 + c - startCode[i] ) glyphIndex = idRangeOffset[ i + idRangeOffset[i] / 2 + c - startCode[i] ] */ for( c=start; c != stop; c++ ) { uint16 k = idro / 2 + c - start; /* + s ??? */ if ( k < max_k ) { k = id_range_offset[k]; if ( k != 0 ) n_valid += set_cmap_entry( font, c, ( idde + k ) & 0xFFFF ); } } } else { /* glyphIndex = idDelta[i] + c, a <= c <= b */ for( c=start; c != stop; c++ ) n_valid += set_cmap_entry( font, c, ( idde + c ) & 0xFFFF ); } } if ( DEBUG_DUMP ) { printf( "Success (%u/%u indices set, %u/%u segs)\n", n_valid, total_indices, (uint) s, (uint) seg_count ); #if USE_BINTREE_CMAP printf( "Binary tree allocated length: %u\n", font->cmap.data_len ); #endif } free( whole_table ); return F_SUCCESS; } FontStatus read_cmap( FILE *fp, Font *font ) { struct { uint16 version, num_tables; } h; long cmap_header_start = ftell( fp ); int has_read_cmap = 0; FontStatus status = F_FAIL_INCOMPLETE; if ( read_shorts( fp, &h.version, 2 ) ) return F_FAIL_EOF; if ( h.version != 0 ) return F_FAIL_UNSUP_VER; (void) font->cmap.data_len; /* just to make sure font->cmap is still a NibTree */ memset( &font->cmap, 0, sizeof( font->cmap ) ); while( h.num_tables-- ) { uint32 temp[2]; uint32 subtable_offset; uint32 plat_enc; /* combined platform and specific encoding */ long next_tabh_pos; if ( fread( temp, 4, 2, fp ) != 2 ) return F_FAIL_EOF; plat_enc = ntohl( temp[0] ); subtable_offset = cmap_header_start + ntohl( temp[1] ); next_tabh_pos = ftell( fp ); if ( fseek( fp, subtable_offset, SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; else { struct { uint16 format, length; } q; if ( read_shorts( fp, &q.format, 2 ) ) return F_FAIL_EOF; if ( DEBUG_DUMP ) { printf( "plat_enc = %08x | platform = %u | encoding = %u | offset=%08x | format=%d | length=%d\n", plat_enc, plat_enc >> 16, plat_enc & 0xFFFF, subtable_offset, q.format, q.length ); } /* Most common cmap formats seem to be 4 (the most common of all), 6 and 12 So it seems reasonable to support just format 4 and nothing else */ if ( !has_read_cmap && q.format == 4 ) { status = read_cmap_format4( fp, font, q.length ); has_read_cmap = 1; } } if ( fseek( fp, next_tabh_pos, SEEK_SET ) < 0 ) return F_FAIL_IMPOSSIBLE; } return status; } static TrError triangulate_glyphs( Font font[1], size_t first_glyph, size_t last_glyph ) { size_t n; TrError err = TR_SUCCESS; struct Triangulator *trg; trg = triangulator_begin(); if ( !trg ) return TR_ALLOC_FAIL; if ( DEBUG_DUMP ) printf( "Triangulating glyphs [%u ... %u]\n", (uint) first_glyph, (uint) last_glyph ); for( n=first_glyph; n<=last_glyph; n++ ) { SimpleGlyph *glyph = font->glyphs[n]; if ( glyph && IS_SIMPLE_GLYPH( glyph )) { err = triangulate_contours( trg, &glyph->tris ); if ( err != TR_SUCCESS ) { if ( DEBUG_DUMP ) printf( "Triangulation failed. Error code = %u\n", (uint) err ); return err; } free( glyph->tris.end_points ); glyph->tris.end_points = NULL; glyph->tris.num_contours = 0; } } triangulator_end( trg ); return err; } static TrError triangulate_all_glyphs( Font font[1] ) { if ( !font->num_glyphs ) return TR_SUCCESS; if ( font->num_glyphs > 20 && ENABLE_OPENMP ) { extern unsigned omp_get_num_procs( void ); extern unsigned omp_get_thread_num( void ); size_t n, numt = omp_get_num_procs(); size_t batch_size = font->num_glyphs / numt; if ( DEBUG_DUMP ) printf( "Using %d omp threads\n", (uint) numt ); #pragma omp parallel for for( n=0; n<numt; n++ ) { size_t start = n * batch_size; size_t end = start + batch_size - 1; if ( omp_get_thread_num() == numt - 1 ) end = font->num_glyphs - 1; triangulate_glyphs( font, start, end ); } /* errors ignored when using openmp */ return TR_SUCCESS; } return triangulate_glyphs( font, 0, font->num_glyphs - 1 ); } static FontStatus read_hmtx( FILE *fp, Font font[1], unsigned num_hmetrics ) { LongHorzMetrics *hmetrics = NULL; FontStatus status; int size_test[ sizeof(*hmetrics) == 4 ]; (void) size_test; if ( font->num_glyphs == 0 ) return F_SUCCESS; hmetrics = malloc( font->num_glyphs * 4 ); if ( !hmetrics ) return F_FAIL_ALLOC; status = F_FAIL_EOF; if ( read_shorts( fp, &hmetrics[0].adv_width, 2 * num_hmetrics ) ) goto error_handler; if ( num_hmetrics < font->num_glyphs ) { uint16 last_adv_x = hmetrics[ num_hmetrics - 1 ].adv_width; size_t n, num_lsb, end; num_lsb = font->num_glyphs - num_hmetrics; end = num_hmetrics + num_lsb; status = F_FAIL_EOF; for( n=num_hmetrics; n<end; n++ ) { int16 lsb; if ( fread( &lsb, 2, 1, fp ) != 1 ) goto error_handler; hmetrics[n].adv_width = last_adv_x; hmetrics[n].lsb = ntohs( lsb ); } } font->hmetrics = hmetrics; return F_SUCCESS; error_handler:; free( hmetrics ); return status; } /* Assumes that the file is positioned after the very first field of Offset Table (sfnt version) */ static FontStatus read_offset_table( FILE *fp, Font font[1] ) { /* Indices of the tables we are interested in. table_pos and table_len are accessed with these */ enum { TAB_HEAD=0, TAB_MAXP, TAB_LOCA, TAB_GLYF, TAB_CMAP, TAB_HHEA, TAB_HMTX, /* TAB_VHEA, TAB_VMTX, */ NUM_USED_TABLES }; uint32 table_pos[NUM_USED_TABLES] = {0}; uint16 n, num_tables, num_glyphs; HeadTable head = {0}; MaxProTableOne maxp = {0}; HorzHeaderTable hhea = {0}; int status; if ( read_shorts( fp, &num_tables, 1 ) ) return F_FAIL_EOF; /* Skip rest of the offset table header */ if ( fseek( fp, 3*2, SEEK_CUR ) < 0 ) return F_FAIL_EOF; for( n=0; n<num_tables; n++ ) { /* TableRecord */ struct { uint32 tag; uint32 checksum; uint32 file_offset; uint32 length; } rec; int tab_num; if ( fread( &rec, 4, 4, fp ) != 4 ) return F_FAIL_EOF; /* todo: remove this ntohl and convert the constants instead */ switch( ntohl( rec.tag ) ) { case 0x68656164: tab_num = TAB_HEAD; break; case 0x6d617870: tab_num = TAB_MAXP; break; case 0x6c6f6361: tab_num = TAB_LOCA; break; case 0x676c7966: tab_num = TAB_GLYF; break; case 0x636d6170: tab_num = TAB_CMAP; break; case 0x68686561: tab_num = TAB_HHEA; break; case 0x686d7478: tab_num = TAB_HMTX; break; default: if ( DEBUG_DUMP ) { /* todo */ printf( "unsupported table: %.4s\n", (char*) &rec.tag ); } continue; } table_pos[ tab_num ] = ntohl( rec.file_offset ); /* table_len[ tab_num ] = ntohl( rec.length ); */ /* todo: verify checksum */ } for( n=0; n<NUM_USED_TABLES; n++ ) { if ( !table_pos[n] ) { /* Missing important tables */ return F_FAIL_INCOMPLETE; } } /* Read table: "head" */ if ( fseek( fp, table_pos[TAB_HEAD], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; if ( fread( &head, 54, 1, fp ) != 1 ) return F_FAIL_EOF; if ( head.magic != htonl( 0x5F0F3CF5 ) ) return F_FAIL_CORRUPT; /* Read table: "maxp" */ if ( fseek( fp, table_pos[TAB_MAXP], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; if ( fread( &maxp, 6, 1, fp ) != 1 ) return F_FAIL_EOF; if ( maxp.version == htonl( 0x5000 ) ) { /* maxp version 0.5 */ } else if ( maxp.version == htonl( 0x10000 ) ) { /* maxp version 1.0 */ if ( fread( &maxp.max_points, 26, 1, fp ) != 1 ) return F_FAIL_EOF; } else { /* unsupported maxp version */ return F_FAIL_UNSUP_VER; } num_glyphs = ntohs( maxp.num_glyphs ); font->units_per_em = ntohs( head.units_per_em ); if ( DEBUG_DUMP ) { printf( "Font statistics:\n" "Version: %08x\n" "Revision: %08x\n" "Tables: %hu\n" "head / Flags: %08hx\n" "head / Units per EM: %u\n" "maxp 0.5 / Glyphs: %u\n", (uint) ntohl( head.version ), (uint) ntohl( head.font_rev ), (unsigned short) num_tables, ntohs( head.flags ), font->units_per_em, (uint) num_glyphs ); if ( maxp.version == htonl( 0x10000 ) ) { printf( "maxp 1.0 / Max contours %hu\n" "maxp 1.0 / Max points (simple glyph) %hu\n" "maxp 1.0 / Max contours (simple glyph) %hu\n" "maxp 1.0 / Max composite recursion %hu\n", ntohs( maxp.max_contours ), ntohs( maxp.max_points ), ntohs( maxp.max_contours ), ntohs( maxp.max_com_recursion ) ); } } font->num_glyphs = num_glyphs; if (( ( font->glyphs = calloc( num_glyphs, sizeof( font->glyphs[0] ) ) ) == NULL )) return F_FAIL_ALLOC; if ( fseek( fp, table_pos[TAB_LOCA], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; /* Read glyph contours using tables "loca" and "glyf" */ status = read_all_glyphs( fp, font, head.index_to_loc_format, table_pos[TAB_GLYF] ); if ( status != F_SUCCESS ) return status; /* Read table "cmap" */ if ( fseek( fp, table_pos[TAB_CMAP], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; status = read_cmap( fp, font ); if ( status != F_SUCCESS ) return status; /* Read horizontal metrics header */ if ( fseek( fp, table_pos[TAB_HHEA], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; if ( fread( &hhea, sizeof(hhea), 1, fp ) != 1 ) return F_FAIL_EOF; if ( hhea.version != htonl( 0x10000 ) ) return F_FAIL_UNSUP_VER; if ( hhea.metric_data_format ) return F_FAIL_UNSUP_VER; font->horz_ascender = (int16) ntohs( hhea.ascender ); font->horz_descender = (int16) ntohs( hhea.descender ); font->horz_linegap = (int16) ntohs( hhea.linegap ); /* Read horizontal metrics */ if ( fseek( fp, table_pos[TAB_HMTX], SEEK_SET ) < 0 ) return F_FAIL_CORRUPT; status = read_hmtx( fp, font, ntohs( hhea.num_hmetrics ) ); if ( status != F_SUCCESS ) return status; /* todo: handle errors properly for each glyph: read location from the 'loca' table read glyph data group curves into triangles subdivide overlapping triangles generate solid triangles to fill the glyph interior create VBOs for each glyph: upload VBO data read cmap read hhead, hmtx (horizontal metrics) read vhea, vmtx (vertical metrics) Other useful tables: BASE - baseline data. Needed to mix glyphs from different scripts (e.g. some math symbols and CJK) GDEF, GPOS - used to change position of glyphs based on context GSUB - used to replace glyphs based on context JSTF - additional positioning crap post - has some interesting fields: italicAngle, underlinePosition, underlineThickness, isFixedPitch kern - glyph positioning. same as GPOS but less useful? name - font name & family name */ return F_SUCCESS; } static FontStatus read_ttc( FILE *fp, Font font[1] ) { /* the tag "ttcf" has been already consumed */ uint32 h[3]; if ( fread( h, 4, 3, fp ) != 3 ) return F_FAIL_EOF; if ( h[0] != htonl( 0x10000 ) && h[0] != htonl( 0x20000 ) ) { /* unsupported TTC version */ return F_FAIL_UNSUP_VER; } if ( h[1] == 0 ) { /* TTC doesn't contain any fonts. Still a valid TTC though? */ return F_FAIL_INCOMPLETE; } /* The font has at least 1 font - todo: read more than 1 font */ if ( fseek( fp, ntohl( h[2] )+4, SEEK_SET ) < 0 ) { return F_FAIL_CORRUPT; } return read_offset_table( fp, font ); } FontStatus load_ttf_file( struct Font *font, const char filename[] ) { FILE *fp = NULL; uint32 file_ident; FontStatus status; memset( font, 0, sizeof(*font) ); fp = fopen( filename, "rb" ); if ( !fp ) return F_FAIL_OPEN; if ( fread( &file_ident, 4, 1, fp ) != 1 ) { status = F_FAIL_EOF; } else { #define USE_SDL_TIMING 0 #if USE_SDL_TIMING extern uint32 SDL_GetTicks( void ); uint32 t = SDL_GetTicks(); #endif if ( file_ident == htonl( 0x10000 ) ) { /* This is a TrueType font file (sfnt version 1.0) todo: handle other identifiers ("true", "typ1", "OTTO") */ status = read_offset_table( fp, font ); } else if ( file_ident == *(uint32*)"ttcf" ) { /* Is a TrueType Collection */ status = read_ttc( fp, font ); } else { /* Unsupported file format */ status = F_FAIL_UNK_FILEF; } if ( status == F_SUCCESS ) { #if USE_SDL_TIMING t = SDL_GetTicks() - t; printf( "File I/O took %u milliseconds\n", (unsigned) t ); #endif if ( triangulate_all_glyphs( font ) != TR_SUCCESS ) status = F_FAIL_TRIANGULATE; /* Merges contour points, indices and glyph data into large contiguous blocks of memory */ if ( !merge_glyph_data( font ) ) status = F_FAIL_ALLOC; } } fclose( fp ); return status; }
GB_binop__land_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__land_int16 // A.*B function (eWiseMult): GB_AemultB__land_int16 // A*D function (colscale): GB_AxD__land_int16 // D*A function (rowscale): GB_DxB__land_int16 // C+=B function (dense accum): GB_Cdense_accumB__land_int16 // C+=b function (dense accum): GB_Cdense_accumb__land_int16 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__land_int16 // C=scalar+B GB_bind1st__land_int16 // C=scalar+B' GB_bind1st_tran__land_int16 // C=A+scalar GB_bind2nd__land_int16 // C=A'+scalar GB_bind2nd_tran__land_int16 // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = ((x != 0) && (y != 0)) ; // 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_LAND || GxB_NO_INT16 || GxB_NO_LAND_INT16) //------------------------------------------------------------------------------ // 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__land_int16 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__land_int16 ( GrB_Matrix C, const GrB_Matrix B, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__land_int16 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int16_t int16_t bwork = (*((int16_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__land_int16 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *GB_RESTRICT Cx = (int16_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__land_int16 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *GB_RESTRICT Cx = (int16_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__land_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__land_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *GB_RESTRICT C_to_M, const int64_t *GB_RESTRICT C_to_A, const int64_t *GB_RESTRICT C_to_B, const GB_task_struct *GB_RESTRICT TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__land_int16 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int16_t bij = Bx [p] ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__land_int16 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = Ax [p] ; Cx [p] = ((aij != 0) && (y != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__land_int16 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__land_int16 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
truecrypt_fmt_plug.c
/* * TrueCrypt volume support for John The Ripper * * Written by Alain Espinosa <alainesp at gmail.com> in 2012. No copyright * is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the * public domain is deemed null and void, then the software is * Copyright (c) 2012 Alain Espinosa 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. * * There's ABSOLUTELY NO WARRANTY, express or implied. * * (This is a heavily cut-down "BSD license".) * * Updated in Dec, 2014 by JimF. This is a ugly format, and was converted * into a more standard (using crypt_all) format. The PKCS5_PBKDF2_HMAC can * be replaced with faster pbkdf2_xxxx functions (possibly with SIMD usage). * this has been done for sha512. ripemd160 and Whirlpool pbkdf2 header * files have been created. Also, proper decrypt is now done, (in cmp_exact) * and we test against the 'TRUE' signature, and against 2 crc32's which * are computed over the 448 bytes of decrypted data. So we now have a * full 96 bits of hash. There will be no way we get false positives from * this slow format. AES_XTS removed. Also, we now only pbkdf2 over * 64 bytes of data (all that is needed for the 2 AES keys), and that sped * up the crypts A LOT (~3x faster). */ #include <string.h> #include "arch.h" #if FMT_EXTERNS_H extern struct fmt_main fmt_truecrypt; extern struct fmt_main fmt_truecrypt_ripemd160; extern struct fmt_main fmt_truecrypt_ripemd160boot; extern struct fmt_main fmt_truecrypt_sha512; extern struct fmt_main fmt_truecrypt_whirlpool; #elif FMT_REGISTERS_H john_register_one(&fmt_truecrypt); john_register_one(&fmt_truecrypt_ripemd160); john_register_one(&fmt_truecrypt_ripemd160boot); john_register_one(&fmt_truecrypt_sha512); john_register_one(&fmt_truecrypt_whirlpool); #else #include "xts.h" #include "misc.h" #include "memory.h" #include "common.h" #include "formats.h" #include "crc32.h" #include "johnswap.h" #include "loader.h" #include "pbkdf2_hmac_sha512.h" #include "pbkdf2_hmac_ripemd160.h" #include "pbkdf2_hmac_whirlpool.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #ifdef __MIC__ #define OMP_SCALE 4 #else #define OMP_SCALE 1 #endif // __MIC__ #endif // OMP_SCALE #endif // _OPENMP #include "memdbg.h" /* 64 is the actual maximum used by Truecrypt software as of version 7.1a */ #define PLAINTEXT_LENGTH 64 #define MAX_CIPHERTEXT_LENGTH (512*2+32) #define SALT_SIZE sizeof(struct cust_salt) #define SALT_ALIGN 4 #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static unsigned char (*key_buffer)[PLAINTEXT_LENGTH + 1]; static unsigned char (*first_block_dec)[16]; #define TAG_WHIRLPOOL "truecrypt_WHIRLPOOL$" #define TAG_SHA512 "truecrypt_SHA_512$" #define TAG_RIPEMD160 "truecrypt_RIPEMD_160$" #define TAG_RIPEMD160BOOT "truecrypt_RIPEMD_160_BOOT$" #define TAG_WHIRLPOOL_LEN (sizeof(TAG_WHIRLPOOL)-1) #define TAG_SHA512_LEN (sizeof(TAG_SHA512)-1) #define TAG_RIPEMD160_LEN (sizeof(TAG_RIPEMD160)-1) #define TAG_RIPEMD160BOOT_LEN (sizeof(TAG_RIPEMD160BOOT)-1) #define IS_SHA512 1 #define IS_RIPEMD160 2 #define IS_WHIRLPOOL 3 #define IS_RIPEMD160BOOT 4 // borrowed from https://github.com/bwalex/tc-play #define MAX_PASSSZ 64 #define PASS_BUFSZ 256 #define KPOOL_SZ 64 #define MAX_KFILE_SZ 1048576 /* 1 MB */ #define MAX_KEYFILES 256 // keyfile(s) data unsigned char (*keyfiles_data)[MAX_KFILE_SZ]; int (*keyfiles_length); static int *cracked; struct cust_salt { unsigned char salt[64]; // I 'thought' that bin[] could be removed, so that only salt[] was used // for salt dupe-removal. That was wrong, bin[] must also be part of the // salt dupe logic, or we will get wrong passwords found, if there is // hashes with the same salts. bin[] array really is part of the salt // since we decrypt it, to do the final check. So there is no real way // to have any duplicate salts. in essense, we have a 'fixed' binary // and the salt is the entire input hash. The fixed binary can be // thought of as 'TRUE' (but it is more than this). It is simply we // do not know the real binary until after we correctly decrypt. // Initially I moved bin[] and ported to dyna_salt. All hashes in a // test suite cracked, BUT the same password was used for all of them, // the first password in the file. Not what we wanted. unsigned char bin[512-64]; int loop_inc; int num_iterations; int hash_type; int nkeyfiles; } *psalt; static struct fmt_tests tests_ripemd160[] = { {"truecrypt_RIPEMD_160$b9f118f89d2699cbe42cad7bc2c61b0822b3d6e57e8d43e79f55666aa30572676c3aced5f0900af223e9fcdf43ac39637640977f546eb714475f8e2dbf5368bfb80a671d7796d4a88c36594acd07081b7ef0fbead3d3a0ff2b295e9488a5a2747ed97905436c28c636f408b36b0898aad3c4e9566182bd55f80e97a55ad9cf20899599fb775f314067c9f7e6153b9544bfbcffb53eef5a34b515e38f186a2ddcc7cd3aed635a1fb4aab98b82d57341ec6ae52ad72e43f41aa251717082d0858bf2ccc69a7ca00daceb5b325841d70bb2216e1f0d4dc936b9f50ebf92dbe2abec9bc3babea7a4357fa74a7b2bcce542044552bbc0135ae35568526e9bd2afde0fa4969d6dc680cf96f7d82ec0a75b6170c94e3f2b6fd98f2e6f01db08ce63f1b6bcf5ea380ed6f927a5a8ced7995d83ea8e9c49238e8523d63d6b669ae0d165b94f1e19b49922b4748798129eed9aa2dae0d2798adabf35dc4cc30b25851a3469a9ee0877775abca26374a4176f8d237f8191fcc870f413ffdbfa73ee22790a548025c4fcafd40f631508f1f6c8d4c847e409c839d21ff146f469feff87198bc184db4b5c5a77f3402f491538503f68e0116dac76344b762627ad678de76cb768779f8f1c35338dd9f72dcc1ac337319b0e21551b9feb85f8cac67a2f35f305a39037bf96cd61869bf1761abcce644598dad254990d17f0faa4965926acb75abf", "password" }, {"truecrypt_RIPEMD_160$6ab053e5ebee8c56bce5705fb1e03bf8cf99e2930232e525befe1e45063aa2e30981585020a967a1c45520543847cdb281557e16c81cea9d329b666e232eeb008dbe3e1f1a181f69f073f0f314bc17e255d42aaa1dbab92231a4fb62d100f6930bae4ccf6726680554dea3e2419fb67230c186f6af2c8b4525eb8ebb73d957b01b8a124b736e45f94160266bcfaeda16b351ec750d980250ebb76672578e9e3a104dde89611bce6ee32179f35073be9f1dee8da002559c6fab292ff3af657cf5a0d864a7844235aeac441afe55f69e51c7a7c06f7330a1c8babae2e6476e3a1d6fb3d4eb63694218e53e0483659aad21f20a70817b86ce56c2b27bae3017727ff26866a00e75f37e6c8091a28582bd202f30a5790f5a90792de010aebc0ed81e9743d00518419f32ce73a8d3f07e55830845fe21c64a8a748cbdca0c3bf512a4938e68a311004538619b65873880f13b2a9486f1292d5c77116509a64eb0a1bba7307f97d42e7cfa36d2b58b71393e04e7e3e328a7728197b8bcdef14cf3f7708cd233c58031c695da5f6b671cc5066323cc86bb3c6311535ad223a44abd4eec9077d70ab0f257de5706a3ff5c15e3bc2bde6496a8414bc6a5ed84fe9462b65efa866312e0699e47338e879ae512a66f3f36fc086d2595bbcff2e744dd1ec283ba8e91299e62e4b2392608dd950ede0c1f3d5b317b2870ead59efe096c054ea1", "123" }, {"truecrypt_RIPEMD_160$76707c2caebf50bdc10a0f010276302299fcd07358130a8c7ddc86bd31b816b957c69f8aae7422a3e1b8dff4853d9090a818aa25801b96ac584cb37190d7d5e376a62fd08629e6416b7ee24150f8e7b963a8e7f5e9b0b71c55e84977cf03c0215c48538229e6449ba6f7dddc0db1498d39661dee4bd48cf3652459591c5300b685335dde79c5e77023bba2fc5aec436f05e23966f97b097f7f9a5b985fb7b72dd2623c3a2df694b55298b6f4c4517d119d3782d8ee644c7206678e06ec4c6eb0dc7f5c89f633cf8f77310e5e5fb8163cf6ca720a29aec1bd22abeb9a1af0fbb009c3ad7579269e747bb400f66b93e3970bae417580deb5956849314e0db1a340f78e6a5a56bb763b98dbca504825d2be2232792ff659e62ca13f2839a15bebc403305a43092dd03d2cbb3e9acc68bdf1397c48f8675de11b9230401ee97ce5c2a9bd7c4eff3e5fba7ce37f6e4ce78669fb6d3eebb9af701f8e288db98a83d4c3fdc5d816fa12693f62fe75324d5e01de459ee5f53dab714d1cf6e6da6c49f04b78c2f5dc72adcaf1a51bf85da90b5a8afdbeceb788e547893a4c284d0699a9f48c866fad8c347ecfc1a37c01f5e6fd19cbfc391d1cf89d291a320a20547a52bdb015674c9913d38f61b673573a2570f1cdf3561309434252d867c86974e945fa703e74bcbf2431a2b55bb6b4e957af3a6acd71b8e55e17f29e5654e50dc5f137", "hashcat"}, // hashcat_ripemd160_twofish.tc {"truecrypt_RIPEMD_160$9450ade46ed2f40e1579c844dbe2c81298cd9dfd911d6c6e44eac4fb919198ce02f6ecbc70bb6fdddce4dcb834b6356b59fa974d5e30e32e4a53e552def9268a03f9bad1cd2d7ead53a9db15f08bb26b8bb3cda95976f73721b0b19e64f9fac2c9e3710c0e88e0a04ef112ab6b2190578873dfdaddd2f146eeb8378185b7f5ac8c9488b8cf2f794330a66b3f37614b702f3fe471bed923cba59fd3845ddecce1da8557f06636f3e9ab5e87d71e2bfa61bd9bc29ee9d3ea27fe84aa8cd7f0b71069a8aaf64b0566ef126c9aec1d6380010cdf1e9da7982b99552503108286bd26ebb2638ca3f594277233b3c1c75361f9c2df448d247dc62c0050cbea7427a48d4bcfc78f227cc38c4b3bdd61c7538de91f6c20728e8af42eb2d92a7b1b0de8469ccb2fadbb60dc4d23b6707482c95b4b4f68c7d7037f52b9a16f80fe643541b11f756c8c3d9a3f231898d71b326455e3719863a78fed5264ea71c6223b58eeebfb2b0ea1c831557e9efe4bd684694a4e79f565fb2615b705bad692314a0519943a718b253bf920453d36382eb04f5adf4cf3e8f471934bd9a39997d8a2418e7320ac32a6470637f22b66b9e72e3d43f26cd5083ac6fb80d20c799dcc01127ba19659b5188644df41071b30de743df3c9670bb86e37f1751c8c02d21c9eda60c2653293b7d3f9480fc13d46d5d89c8737d541c385fea823a147c96a129047e127", "hashcat"}, // hashcat_ripemd160_serpent.tc {NULL} }; static struct fmt_tests tests_ripemd160boot[] = { {"truecrypt_RIPEMD_160_BOOT$2b5da9924119fde5270f712ba3c3e4974460416e8465f222149499908c2fca0a4753b581f26625d11c4d3f49bdeb1c95bc3e17629d7e19ffb66175e5feab90a4fd670194f95d578266f3f54e61b82dc00efc2bb4438e19c3f6d7a92825a7625d88ec6286ab4e1761749edc83dad4340fd167544f09913fd6b03775013ff232fc4dad6f726ef82ad4bd1c5227a7796d7db35a912beeda5b0cdd798bc34d3ac24403c87dc672a983687dd64f920c991840a56105a6311797eed9976014909700366420673f6455242c71151ac75903a353538ec24b4feb967e2b46886395cf3e934e83a6a58ef2c0180273a0c33ba2bd870b1d84afb03d5558dc17bc7fb586404ad9a7e506ed859540110c6ad73f0f1d2be47829bc666e1838ec3f1dc1f610206241ce07fbf2542ecef9348b37aa460815794ca582709697cbf0c90c3dae4cb9dd97b29d3c7d82bd8d0c81d708e74c7007468c6c55a40fd4f803a4f5a75818d7da0d1ef333b8622e7de516fa62a6fa2b8d6d5d23653dfcedffec771456ee204e5c85ee88defbe195462fbe8ce0e2a5a455dab66478b877ec37dfa66f19ab5201c56cd707ba7bee1b10360965d3868c1fdf91dda124b1b0994fee75848083d19369735905bd2864b496c6e35ecf96f6dd4728570a45746bcf8d7d0ec0b9b0b112b28fdc53efcfa7d0558c132cd683a742d62b34304d9f991029c8aedc3d8767da8c", "hashcat"}, // hashcat_ripemd160_aes_boot.tc {"truecrypt_RIPEMD_160_BOOT$3f6e7171e8c7d0f6ba03defcfbdef5de8d43984b21c3422bbce2357e1434334ac8af920e736ba4006094ad426524ceb491248a381ea154c37889a916f40c4823b4c68bcfbf8548b93830411a8b27746c6dd99c2a1ed0920947139a54fcf6315965730e85f9b8ced69a7f1c4336c63a351606ea577b8a5caa6b86cdac846534ba62735170350ad89c1f355165690439c4d0d8f6c6b2d0ef5f68958a10edac4b553d070f27e34291141b85e4502ae12721a8e7cb8bb1e8b8bfd57e4a92ab5364d4bb3415cfb1d12620ec17a6de1b050df122c03210b723fffc477c4d5b65319a269ae9dc18bd2fa55d2bc00b23b3824ddbfa7941fdee4a99afda93bb34bd7b613a9f2db7ec5f2947dfadf8fec021e9cb6d5acd2d23bf86f9fb699eb7faed555ff32be301f0ac35020221528808f1c00c95b14b791bf678dc234a339ac0c7c1c8131caecfabd2778e26503a967a592b5f36173e763b2d7db7f826a36368e7e88eb8c7d587b6a1eae544800f499ff0b4937cfa07861331e699265e61081a612c0075ff95f77ea9be731cc2aa285024548c506d2e89acd07f39250238e2f4e319b789ca7d4163482211839787c9cdd3189c7a4525d4e2e38d7f5affb2ed5d7cf3de9ea14c50f51a2f307248758e6eca8179cb8e2d7397f6b1818a9c25131b7fac5c12efc5e952e8e04af9fb3432548378b4a20471fad934cd7c9983af7830e2f6a202", "hashcat"}, // hashcat_ripemd160_twofish_boot.tc {"truecrypt_RIPEMD_160_BOOT$e4cad3bc157ded7d28b8111f6967617a1e920bc4238fd2293b0f6f943d692e97b9b4ab9f75df7010cdbd1d20cf9775b85aad6101ac2ca499c7d592ce8c47fb16c01146d61f54457b15d9a70683713437671fd8ca0b83175058072d34f5737b59caf8b63f6244cb95d748cea3589111d20b73d2750d7fd18a791dd85aa96a6c65d5387f08c80f735824833314ca98ac5d1a52e055fb2bac663457b248aec33773fbb0b73586d62d2e44991ebf68af4fab38954385d9addd88e03f819ccf959d502888a70edc01d0a924f957fd3f8db037f0c65068ab46ccd00ac12df649c9735e20bd3d5411d0285918926a23a6d9b8dff315d245b6156fe49ef5ebcc35b98c43568cdf4585e9d96d9b3e9d252df2f34528a9bc9739ca4c906bbcea34f6704cf417493067839183c85c6553ab1ecbb552b85434c892154f0fe341f7b7f21a4052619b77db2be345ddd01b6ecc72eb424a78fc10379785fba362a2a86f1a9660fc0bb5408516571c103983ea5d43f7fae5688a59ef1ac913c96012c66dbb67f86aaff82fe52dc4ac3ba4c7737efbfae84de2138bc41650bb62fa41232f5e7a51f3a07316234d1ebe2cfee38380902aae2d338653bff0fd97f83d971c9193870734a2b0f16ac52aaa4c4f1c29fc7e6619cacbf72fed79f3ad3db214b0e32a56c5283865c3af8d8c17f76e608309ab266abd4abad72d0cc96e4c6453a4633ee86aa9", "hashcat"}, // hashcat_ripemd160_serpent_boot.tc {NULL}, }; static struct fmt_tests tests_sha512[] = { {"truecrypt_SHA_512$aa582afe64197a3cfd4faf7697673e5e14414369da3f716400414f63f75447da7d3abdc65a25ea511b1772d67370d6c349d8000de66d65861403093fecfb85719e1d46158d24324e5a2c0ee598214b1b2e7eac761dbde8cb85bcb33f293df7f30c9e44a3fa97bf1c70e9986677855873fa2435d9154ccaed8f28d68f16b10adcce7032d7c1742d322739d02c05457859abdaa176faa95c674d2a1092c30832dd2afd9a319599b4d1db92ffe6e48b3b29e566d5c51af091839699f5ad1715730fef24e94e39a6f40770b8320e30bf972d810b588af88ce3450337adbec0a10255b20230bcfca93aa5a0a6592cd6038312181c0792c59ec9e5d95a6216497d39ae28131869b89368e82371718970bf9750a7114c83d87b1b0cd16b6e8d41c4925d15ec26107e92847ec1bb73363ca10f3ad62afa8b0f95ff13cdbe217a1e8a74508ef439ed2140b26d5538b8d011a0d1e469f2a6962e56964adc75b90d9c6a16e88ad0adb59a337f8abb3f9d76f7f9acad22853e9dbbce13a4f686c6a802243b0901972af3c6928511609ac7b957b352452c4347acd563a72faa86a46522942fdc57f32d48c5148a2bb0bc2c3dbc9851385f816f2ece958957082c0a8fe69f647be675d87fcb8244912abc277a3242ee17e1d522f85598417559cb3a9f60b755e5b613069cb54c05a4c5d2fbd3ca6ba793320aeb0e109f8b21852daf2d9ed74dd9", "password"}, {"truecrypt_SHA_512$73f6b08614dc4ffbd77d27a0815b0700d6b612f573ccd6c8937e8d154321e3c1c1c67dd348d4d3bc8304e94a3a6ec0c672de8396a9a6b26b12393195b7daa4225a9d3a134229be011f8179791bb00c31b5c132c8dbad5a6f8738487477c409b3c32d90b07be8d7a3a9faa95d37ab6faccc459d47f029e25adcea48cee83eaa35b7acc3f849717000421d92ac46e6f16ec3dccacd3ffae76a48280977d2a6727027d9d6ff9c4c98405359ee382f6dd1eca0d7007cbe804b81485c1085e74b58d3eb1e3c7ebdc1e1ab1384e4440ab6ca7beed7e0ef7d1e0da5ffc3cd89f7b6ac8a9257ee369d397ac1e112f75382ddbe6f7317ec20c46cb7b2111d0d91570e90b4c01a0b8205fcdf4d0cadcf4a067b8f285a541f1d649894fb3ade29a2ee0575524455d489c299dde215bea3254f7d43aa4e4011a39bdb6e7473bc29f588e659fdbf065cc4a336ba42f2b6c07479cf3e544978150fb013da7db22afcb4f8384e39e2edfa30a4cbe5e84a07c54ba66663bb9284836cc5a8ba7489d3f7f92aec6d9f4e264c90c2af6181082bd273197bc42c325cb1de31006dd55425e3f210d2ddd7973978eec865d3226bb1e30a9897146d90d79a73070e87f0182981ea85f15f948ae1958af7704fabecd6f07e20be70be9f9c38a5c5e5c8b17be648f011b2c40f62d6ac51de932add5bdb47bb428fd510b004a7aa79321b03ed7aa202be439fbf", "password" }, {"truecrypt_SHA_512$cfd9e5757da139b32d117cd60f86f649400615dc218981106dfadd44598599a7ec0ace42de61506fe8d81b5c885861cdb26e0c38cb9adfcff27ba88872220ccd0914d4fa44bab5a708fe6864e0f665ac71d87e7e97b3724d610cf1f6ec09fa99da40126f63868654fed3381eaa8176f689e8e292c3cb68e43601d5804bc2e19d86722c21d42204e158b26b720e7b8f7580edce15469195dd7ed711b0fcb6c8abc253d0fd93cc784d5279de527fbdcfb357780635a5c363b773b55957d7efb472f6e6012489a9f0d225573446e5251cfb277a1365eed787e0da52f02d835667d74cc41fa4002cc35ad1ce276fbf9d73d6553ac0f8ab6961901d292a66df814a2cbda1b41f29aeec88ed15e7d37fe84ac5306b5a1b8d2e1f2c132e5c7d40ca7bb76d4ff87980ca4d75eaac5066b3ed50b53259554b9f922f7cee8e91847359d06e448da02cbeeecc78ca9bee2899a33dfa04a478ca131d33c64d6de5f81b219f11bed6ff3c0d56f26b3a27c79e7c55b6f76567a612166ce71028e3d3ae7e5abd25faec5e2e9dc30719baa2c138e26d6f8e3799a72b5e7b1c2a07c12cea452073b72f6e429bb17dd23fe3934c9e406bb4060083f92aa100c2e82ca40664f65c02cbc800c5696659f8df84db17edb92de5d4f1ca9e5fe71844e1e8c4f8b19ce7362fb3ca5467bf65122067c53f011648a6663894b315e6c5c635bec5bd39da028041", "123" }, /* test vector with single keyfile, with data "1234567" */ {NULL} }; static struct fmt_tests tests_whirlpool[] = { {"truecrypt_WHIRLPOOL$5724ba89229d705010ec56af416b16155682a0cab9cf48ac5a5fdd2086c9a251ae4bbea6cfb8464321a789852f7812095b0e0c4c4f9c6d14ba7beedaf3484b375ac7bc97b43c3e74bf1a0c259b7ac8725d990d2ff31935ca3443f2ce8df59de86515da3e0f53f728882b71c5cc704df0c87c282a7413db446e9a2e516a144311dd25092eb0a2c5df0240d899708289fc7141abd8538fa5791d9f96c39129cce9fe8a6e58e84364e2f4acc32274147431cb2d2480b1b54bffee485acee0925852b8a6ee71d275f028b92e540be595448e5f1d78560a3b8ad209962dd5981d7ca98db9a678a588a9296157d44502cd78f9e32f022dddc9bc8111b5704ee39a9b56d30b89898ae340e90f2e6c73be6ac64de97e32fc2eed0b66dcd5c1553eeab3950cf851624a5a4439435a6fd5717fda6d5f939f4a902321341964c16bda8975752ba150fb9d858d8eaff2a2086cb50d30abff741ee20223b4223b1783f0ed537a609a081afed952395ef0b5de6883db66cbb5a8bac70f2f757c7b6e6bb5d863672820f0d3d61b262b2b6c2ca0dc8e7137851aa450da1c1d915e005bff0e849a89bf67693ef97f5c17bf8d07a18c562dc783274f9ec580f9519a6dd1429b66160ddb04549506ad616dd0695da144fa2ad270eac7163983e9036f1bde3c7634b8a246b8dcd518ce3e12b881c838fbce59a0cfdffa3b21447e3f28124f63549c3962", "password" }, {"truecrypt_WHIRLPOOL$0650595770851981d70b088ff6ef4bf90573e08d03c8cac8b2dfded22e1653f5c45103758c68be344fdccae42b4683087da083a3841b92fb79856798eaee793c04cd95ae556d9616684da17e47bd2f775d8128f94b80b781e4cab4921b12c620721cf719ca72d3997cea829fd29b429282b597d5719c13423cdf7bd717fa12a56b8eddcf7b1ad2796c4ad078ab3a9bd944a694aa4b0078ed160440dd3db13dd1d04a7aaaa4dc016a95bd1cfafcd833ae933c627bf5512ae55c76069af7190823dba0133d6fe02e4421d3684ff2a2493da990a3cc5eed40a9e8c48c7a89a2f47030d45c324a3d78b941e772e24b285af6739ae1f5953ff838edaa69e79939f55d0fe00cd0e3a20a46db3a232009eabc800711342f7e580ba909f16c2039d4900fd4025845a385641a6037ceb6420fe7d37868e8c06e6146eddec9e6cb97e71048da5fa5898dac08152516ea1c6729e85d31596cd226aa218ce693989efb9fa8b05404bcc2debbc75c429a03fe31bfc49f10d595b898436ff6b02fc01d745b91280f26ae94a4969ce7f86c12e6b562c7b5377e3fb3247a8cda11a930c2a9e80f24966925de01afad5987ebee9c3de1d41667c6dc35cebbbc963f263c700d06a647ab7020385e3a7e30406f3e7a9b3142d39e0439c98948134d11166b621dfd3ea9d3a84d985b2aa7732b7ad9beba44334dd86292b0c94befb2cb8aa72a823129cb", "123" }, {NULL} }; static struct fmt_tests tests_all[] = { {"truecrypt_SHA_512$aa582afe64197a3cfd4faf7697673e5e14414369da3f716400414f63f75447da7d3abdc65a25ea511b1772d67370d6c349d8000de66d65861403093fecfb85719e1d46158d24324e5a2c0ee598214b1b2e7eac761dbde8cb85bcb33f293df7f30c9e44a3fa97bf1c70e9986677855873fa2435d9154ccaed8f28d68f16b10adcce7032d7c1742d322739d02c05457859abdaa176faa95c674d2a1092c30832dd2afd9a319599b4d1db92ffe6e48b3b29e566d5c51af091839699f5ad1715730fef24e94e39a6f40770b8320e30bf972d810b588af88ce3450337adbec0a10255b20230bcfca93aa5a0a6592cd6038312181c0792c59ec9e5d95a6216497d39ae28131869b89368e82371718970bf9750a7114c83d87b1b0cd16b6e8d41c4925d15ec26107e92847ec1bb73363ca10f3ad62afa8b0f95ff13cdbe217a1e8a74508ef439ed2140b26d5538b8d011a0d1e469f2a6962e56964adc75b90d9c6a16e88ad0adb59a337f8abb3f9d76f7f9acad22853e9dbbce13a4f686c6a802243b0901972af3c6928511609ac7b957b352452c4347acd563a72faa86a46522942fdc57f32d48c5148a2bb0bc2c3dbc9851385f816f2ece958957082c0a8fe69f647be675d87fcb8244912abc277a3242ee17e1d522f85598417559cb3a9f60b755e5b613069cb54c05a4c5d2fbd3ca6ba793320aeb0e109f8b21852daf2d9ed74dd9", "password"}, {"truecrypt_SHA_512$73f6b08614dc4ffbd77d27a0815b0700d6b612f573ccd6c8937e8d154321e3c1c1c67dd348d4d3bc8304e94a3a6ec0c672de8396a9a6b26b12393195b7daa4225a9d3a134229be011f8179791bb00c31b5c132c8dbad5a6f8738487477c409b3c32d90b07be8d7a3a9faa95d37ab6faccc459d47f029e25adcea48cee83eaa35b7acc3f849717000421d92ac46e6f16ec3dccacd3ffae76a48280977d2a6727027d9d6ff9c4c98405359ee382f6dd1eca0d7007cbe804b81485c1085e74b58d3eb1e3c7ebdc1e1ab1384e4440ab6ca7beed7e0ef7d1e0da5ffc3cd89f7b6ac8a9257ee369d397ac1e112f75382ddbe6f7317ec20c46cb7b2111d0d91570e90b4c01a0b8205fcdf4d0cadcf4a067b8f285a541f1d649894fb3ade29a2ee0575524455d489c299dde215bea3254f7d43aa4e4011a39bdb6e7473bc29f588e659fdbf065cc4a336ba42f2b6c07479cf3e544978150fb013da7db22afcb4f8384e39e2edfa30a4cbe5e84a07c54ba66663bb9284836cc5a8ba7489d3f7f92aec6d9f4e264c90c2af6181082bd273197bc42c325cb1de31006dd55425e3f210d2ddd7973978eec865d3226bb1e30a9897146d90d79a73070e87f0182981ea85f15f948ae1958af7704fabecd6f07e20be70be9f9c38a5c5e5c8b17be648f011b2c40f62d6ac51de932add5bdb47bb428fd510b004a7aa79321b03ed7aa202be439fbf", "password" }, {TAG_SHA512"cfd9e5757da139b32d117cd60f86f649400615dc218981106dfadd44598599a7ec0ace42de61506fe8d81b5c885861cdb26e0c38cb9adfcff27ba88872220ccd0914d4fa44bab5a708fe6864e0f665ac71d87e7e97b3724d610cf1f6ec09fa99da40126f63868654fed3381eaa8176f689e8e292c3cb68e43601d5804bc2e19d86722c21d42204e158b26b720e7b8f7580edce15469195dd7ed711b0fcb6c8abc253d0fd93cc784d5279de527fbdcfb357780635a5c363b773b55957d7efb472f6e6012489a9f0d225573446e5251cfb277a1365eed787e0da52f02d835667d74cc41fa4002cc35ad1ce276fbf9d73d6553ac0f8ab6961901d292a66df814a2cbda1b41f29aeec88ed15e7d37fe84ac5306b5a1b8d2e1f2c132e5c7d40ca7bb76d4ff87980ca4d75eaac5066b3ed50b53259554b9f922f7cee8e91847359d06e448da02cbeeecc78ca9bee2899a33dfa04a478ca131d33c64d6de5f81b219f11bed6ff3c0d56f26b3a27c79e7c55b6f76567a612166ce71028e3d3ae7e5abd25faec5e2e9dc30719baa2c138e26d6f8e3799a72b5e7b1c2a07c12cea452073b72f6e429bb17dd23fe3934c9e406bb4060083f92aa100c2e82ca40664f65c02cbc800c5696659f8df84db17edb92de5d4f1ca9e5fe71844e1e8c4f8b19ce7362fb3ca5467bf65122067c53f011648a6663894b315e6c5c635bec5bd39da028041", "123" }, {"truecrypt_RIPEMD_160$b9f118f89d2699cbe42cad7bc2c61b0822b3d6e57e8d43e79f55666aa30572676c3aced5f0900af223e9fcdf43ac39637640977f546eb714475f8e2dbf5368bfb80a671d7796d4a88c36594acd07081b7ef0fbead3d3a0ff2b295e9488a5a2747ed97905436c28c636f408b36b0898aad3c4e9566182bd55f80e97a55ad9cf20899599fb775f314067c9f7e6153b9544bfbcffb53eef5a34b515e38f186a2ddcc7cd3aed635a1fb4aab98b82d57341ec6ae52ad72e43f41aa251717082d0858bf2ccc69a7ca00daceb5b325841d70bb2216e1f0d4dc936b9f50ebf92dbe2abec9bc3babea7a4357fa74a7b2bcce542044552bbc0135ae35568526e9bd2afde0fa4969d6dc680cf96f7d82ec0a75b6170c94e3f2b6fd98f2e6f01db08ce63f1b6bcf5ea380ed6f927a5a8ced7995d83ea8e9c49238e8523d63d6b669ae0d165b94f1e19b49922b4748798129eed9aa2dae0d2798adabf35dc4cc30b25851a3469a9ee0877775abca26374a4176f8d237f8191fcc870f413ffdbfa73ee22790a548025c4fcafd40f631508f1f6c8d4c847e409c839d21ff146f469feff87198bc184db4b5c5a77f3402f491538503f68e0116dac76344b762627ad678de76cb768779f8f1c35338dd9f72dcc1ac337319b0e21551b9feb85f8cac67a2f35f305a39037bf96cd61869bf1761abcce644598dad254990d17f0faa4965926acb75abf", "password" }, {TAG_RIPEMD160"6ab053e5ebee8c56bce5705fb1e03bf8cf99e2930232e525befe1e45063aa2e30981585020a967a1c45520543847cdb281557e16c81cea9d329b666e232eeb008dbe3e1f1a181f69f073f0f314bc17e255d42aaa1dbab92231a4fb62d100f6930bae4ccf6726680554dea3e2419fb67230c186f6af2c8b4525eb8ebb73d957b01b8a124b736e45f94160266bcfaeda16b351ec750d980250ebb76672578e9e3a104dde89611bce6ee32179f35073be9f1dee8da002559c6fab292ff3af657cf5a0d864a7844235aeac441afe55f69e51c7a7c06f7330a1c8babae2e6476e3a1d6fb3d4eb63694218e53e0483659aad21f20a70817b86ce56c2b27bae3017727ff26866a00e75f37e6c8091a28582bd202f30a5790f5a90792de010aebc0ed81e9743d00518419f32ce73a8d3f07e55830845fe21c64a8a748cbdca0c3bf512a4938e68a311004538619b65873880f13b2a9486f1292d5c77116509a64eb0a1bba7307f97d42e7cfa36d2b58b71393e04e7e3e328a7728197b8bcdef14cf3f7708cd233c58031c695da5f6b671cc5066323cc86bb3c6311535ad223a44abd4eec9077d70ab0f257de5706a3ff5c15e3bc2bde6496a8414bc6a5ed84fe9462b65efa866312e0699e47338e879ae512a66f3f36fc086d2595bbcff2e744dd1ec283ba8e91299e62e4b2392608dd950ede0c1f3d5b317b2870ead59efe096c054ea1", "123" }, {"truecrypt_WHIRLPOOL$5724ba89229d705010ec56af416b16155682a0cab9cf48ac5a5fdd2086c9a251ae4bbea6cfb8464321a789852f7812095b0e0c4c4f9c6d14ba7beedaf3484b375ac7bc97b43c3e74bf1a0c259b7ac8725d990d2ff31935ca3443f2ce8df59de86515da3e0f53f728882b71c5cc704df0c87c282a7413db446e9a2e516a144311dd25092eb0a2c5df0240d899708289fc7141abd8538fa5791d9f96c39129cce9fe8a6e58e84364e2f4acc32274147431cb2d2480b1b54bffee485acee0925852b8a6ee71d275f028b92e540be595448e5f1d78560a3b8ad209962dd5981d7ca98db9a678a588a9296157d44502cd78f9e32f022dddc9bc8111b5704ee39a9b56d30b89898ae340e90f2e6c73be6ac64de97e32fc2eed0b66dcd5c1553eeab3950cf851624a5a4439435a6fd5717fda6d5f939f4a902321341964c16bda8975752ba150fb9d858d8eaff2a2086cb50d30abff741ee20223b4223b1783f0ed537a609a081afed952395ef0b5de6883db66cbb5a8bac70f2f757c7b6e6bb5d863672820f0d3d61b262b2b6c2ca0dc8e7137851aa450da1c1d915e005bff0e849a89bf67693ef97f5c17bf8d07a18c562dc783274f9ec580f9519a6dd1429b66160ddb04549506ad616dd0695da144fa2ad270eac7163983e9036f1bde3c7634b8a246b8dcd518ce3e12b881c838fbce59a0cfdffa3b21447e3f28124f63549c3962", "password" }, {TAG_WHIRLPOOL"0650595770851981d70b088ff6ef4bf90573e08d03c8cac8b2dfded22e1653f5c45103758c68be344fdccae42b4683087da083a3841b92fb79856798eaee793c04cd95ae556d9616684da17e47bd2f775d8128f94b80b781e4cab4921b12c620721cf719ca72d3997cea829fd29b429282b597d5719c13423cdf7bd717fa12a56b8eddcf7b1ad2796c4ad078ab3a9bd944a694aa4b0078ed160440dd3db13dd1d04a7aaaa4dc016a95bd1cfafcd833ae933c627bf5512ae55c76069af7190823dba0133d6fe02e4421d3684ff2a2493da990a3cc5eed40a9e8c48c7a89a2f47030d45c324a3d78b941e772e24b285af6739ae1f5953ff838edaa69e79939f55d0fe00cd0e3a20a46db3a232009eabc800711342f7e580ba909f16c2039d4900fd4025845a385641a6037ceb6420fe7d37868e8c06e6146eddec9e6cb97e71048da5fa5898dac08152516ea1c6729e85d31596cd226aa218ce693989efb9fa8b05404bcc2debbc75c429a03fe31bfc49f10d595b898436ff6b02fc01d745b91280f26ae94a4969ce7f86c12e6b562c7b5377e3fb3247a8cda11a930c2a9e80f24966925de01afad5987ebee9c3de1d41667c6dc35cebbbc963f263c700d06a647ab7020385e3a7e30406f3e7a9b3142d39e0439c98948134d11166b621dfd3ea9d3a84d985b2aa7732b7ad9beba44334dd86292b0c94befb2cb8aa72a823129cb", "123" }, {NULL} }; 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 key_buffer = mem_calloc(self->params.max_keys_per_crypt, sizeof(*key_buffer)); first_block_dec = mem_calloc(self->params.max_keys_per_crypt, sizeof(*first_block_dec)); keyfiles_data = mem_calloc(MAX_KEYFILES, sizeof(*keyfiles_data)); keyfiles_length = mem_calloc(MAX_KEYFILES, sizeof(int)); cracked = mem_calloc(sizeof(*cracked), self->params.max_keys_per_crypt); Twofish_initialise(); } static void done(void) { MEM_FREE(first_block_dec); MEM_FREE(key_buffer); MEM_FREE(keyfiles_data); MEM_FREE(keyfiles_length); MEM_FREE(cracked); } static int valid(char* ciphertext, int pos) { unsigned int i; char *p, *q; int nkeyfiles = -1; p = ciphertext + pos; q = strchr(p, '$'); if (!q) { /* no keyfiles */ if (pos + 512 * 2 != strlen(ciphertext)) return 0; } else { if (q - p != 512 * 2) return 0; /* check keyfile(s) */ p = q + 1; nkeyfiles = atoi(p); if (nkeyfiles > MAX_KEYFILES || nkeyfiles < 1) return 0; } // Not hexadecimal characters for (i = 0; i < 512 * 2; i++) { if (atoi16l[ARCH_INDEX((ciphertext+pos)[i])] == 0x7F) return 0; } return 1; } static int valid_ripemd160(char* ciphertext, struct fmt_main *self) { // Not a supported hashing if (strncmp(ciphertext, TAG_RIPEMD160, TAG_RIPEMD160_LEN)) return 0; return valid(ciphertext, TAG_RIPEMD160_LEN); } static int valid_ripemd160boot(char* ciphertext, struct fmt_main *self) { if (strncmp(ciphertext, TAG_RIPEMD160BOOT, TAG_RIPEMD160BOOT_LEN)) return 0; return valid(ciphertext, TAG_RIPEMD160BOOT_LEN); } static int valid_sha512(char* ciphertext, struct fmt_main *self) { // Not a supported hashing if (strncmp(ciphertext, TAG_SHA512, TAG_SHA512_LEN)) return 0; return valid(ciphertext, TAG_SHA512_LEN); } static int valid_whirlpool(char* ciphertext, struct fmt_main *self) { // Not a supported hashing if (strncmp(ciphertext, TAG_WHIRLPOOL, TAG_WHIRLPOOL_LEN)) return 0; return valid(ciphertext, TAG_WHIRLPOOL_LEN); } static int valid_truecrypt(char *ciphertext, struct fmt_main *self) { if (valid_sha512(ciphertext, self) || valid_ripemd160(ciphertext, self) || valid_ripemd160boot(ciphertext, self) || valid_whirlpool(ciphertext, self)) return 1; return 0; } static void set_salt(void *salt) { psalt = salt; } static void* get_salt(char *ciphertext) { static char buf[sizeof(struct cust_salt)+4]; struct cust_salt *s = (struct cust_salt *)mem_align(buf, 4); unsigned int i; char tpath[PATH_BUFFER_SIZE] = {0}; char *p, *q; int idx; FILE *fp; size_t sz; memset(s, 0, sizeof(struct cust_salt)); s->num_iterations = 1000; s->loop_inc = 1; if (!strncmp(ciphertext, TAG_WHIRLPOOL, TAG_WHIRLPOOL_LEN)) { ciphertext += TAG_WHIRLPOOL_LEN; s->hash_type = IS_WHIRLPOOL; } else if (!strncmp(ciphertext, TAG_SHA512, TAG_SHA512_LEN)) { ciphertext += TAG_SHA512_LEN; s->hash_type = IS_SHA512; #if SSE_GROUP_SZ_SHA512 s->loop_inc = SSE_GROUP_SZ_SHA512; #endif } else if (!strncmp(ciphertext, TAG_RIPEMD160, TAG_RIPEMD160_LEN)) { ciphertext += TAG_RIPEMD160_LEN; s->hash_type = IS_RIPEMD160; s->num_iterations = 2000; } else if (!strncmp(ciphertext, TAG_RIPEMD160BOOT, TAG_RIPEMD160BOOT_LEN)) { ciphertext += TAG_RIPEMD160BOOT_LEN; s->hash_type = IS_RIPEMD160BOOT; s->num_iterations = 1000; } else { // should never get here! valid() should catch all lines that do not have the tags. fprintf(stderr, "Error, unknown type in truecrypt::get_salt(), [%s]\n", ciphertext); error(); } // Convert the hexadecimal salt in binary for (i = 0; i < 64; i++) s->salt[i] = (atoi16[ARCH_INDEX(ciphertext[2*i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2*i+1])]; for (; i < 512; i++) s->bin[i-64] = (atoi16[ARCH_INDEX(ciphertext[2*i])] << 4) | atoi16[ARCH_INDEX(ciphertext[2*i+1])]; p = ciphertext; q = strchr(p, '$'); if (!q) /* no keyfiles */ return s; // process keyfile(s) p = q + 1; s->nkeyfiles = atoi(p); for (idx = 0; idx < s->nkeyfiles; idx++) { p = strchr(p, '$') + 1; // at first filename q = strchr(p, '$'); if (!q) { // last file memset(tpath, 0, sizeof(tpath) - 1); strncpy(tpath, p, sizeof(tpath)); } else { memset(tpath, 0, sizeof(tpath) - 1); strncpy(tpath, p, q-p); } /* read this into keyfiles_data[idx] */ fp = fopen(tpath, "rb"); if (!fp) pexit("fopen %s", p); if (fseek(fp, 0L, SEEK_END) == -1) pexit("fseek"); sz = ftell(fp); if (fseek(fp, 0L, SEEK_SET) == -1) pexit("fseek"); if (fread(keyfiles_data[idx], 1, sz, fp) != sz) pexit("fread"); keyfiles_length[idx] = sz; fclose(fp); } return s; } static int apply_keyfiles(unsigned char *pass, size_t pass_memsz, int nkeyfiles) { int pl, k; unsigned char *kpool; unsigned char *kdata; int kpool_idx; size_t i, kdata_sz; uint32_t crc; if (pass_memsz < MAX_PASSSZ) { error(); } pl = strlen((char *)pass); memset(pass+pl, 0, MAX_PASSSZ-pl); if ((kpool = mem_calloc(1, KPOOL_SZ)) == NULL) { error(); } for (k = 0; k < nkeyfiles; k++) { kpool_idx = 0; kdata_sz = keyfiles_length[k]; kdata = keyfiles_data[k]; crc = ~0U; for (i = 0; i < kdata_sz; i++) { crc = jtr_crc32(crc, kdata[i]); kpool[kpool_idx++] += (unsigned char)(crc >> 24); kpool[kpool_idx++] += (unsigned char)(crc >> 16); kpool[kpool_idx++] += (unsigned char)(crc >> 8); kpool[kpool_idx++] += (unsigned char)(crc); /* Wrap around */ if (kpool_idx == KPOOL_SZ) kpool_idx = 0; } } /* Apply keyfile pool to passphrase */ for (i = 0; i < KPOOL_SZ; i++) pass[i] += kpool[i]; MEM_FREE(kpool); return 0; } // compare a BE string crc32, against crc32, and do it in a safe for non-aligned CPU way. // this function is not really speed critical. static int cmp_crc32s(unsigned char *given_crc32, CRC32_t comp_crc32) { return given_crc32[0] == ((comp_crc32>>24)&0xFF) && given_crc32[1] == ((comp_crc32>>16)&0xFF) && given_crc32[2] == ((comp_crc32>> 8)&0xFF) && given_crc32[3] == ((comp_crc32>> 0)&0xFF); } static int decrypt_and_verify(unsigned char *key, int algorithm) { unsigned char decr_header[512-64]; CRC32_t check_sum; // We have 448 bytes of header (64 bytes unencrypted salt were the // first 64 bytes). Decrypt it and look for 3 items. switch (algorithm) { case 0: XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256, 0); break; case 1: XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256, 1); // Twofish_XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256); break; case 2: XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256, 2); // Serpent_XTS_decrypt(key, decr_header, psalt->bin, 512-64, 256); break; } // First item we look for is a contstant string 'TRUE' in the first 4 bytes. if (memcmp(decr_header, "TRUE", 4)) return 0; // Now we look for 2 crc values. At offset 8 is the first. This provided // CRC should be the crc32 of the last 256 bytes of the buffer. CRC32_Init(&check_sum); CRC32_Update(&check_sum, &decr_header[256-64], 256); if (!cmp_crc32s(&decr_header[8], ~check_sum)) return 0; // Now we compute crc of the first part of the buffer, up to 4 bytes less than // the start of that last 256 bytes (i.e. 188 bytes in total). Following this // buffer we compute crc32 over, should be a 4 byte block that is what we are // given as a match for this crc32 (of course, those 4 bytes are not part of // the crc32. The 4 bytes of provided crc32 is the only 4 bytes of the header // which are not placed into 'some' CRC32 computation. CRC32_Init(&check_sum); CRC32_Update(&check_sum, decr_header, 256-64-4); if (!cmp_crc32s(&decr_header[256-64-4], ~check_sum)) return 0; // Passed 96 bits of tests. This is the right password! return 1; } static int crypt_all(int *pcount, struct db_salt *salt) { int i; const int count = *pcount; memset(cracked, 0, sizeof(cracked[0]) * count); #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i+=psalt->loop_inc) { unsigned char key[64]; #if SSE_GROUP_SZ_SHA512 unsigned char Keys[SSE_GROUP_SZ_SHA512][64]; #endif int j; int ksz = strlen((char *)key_buffer[i]); #if SSE_GROUP_SZ_SHA512 if (psalt->hash_type != IS_SHA512) #endif { strncpy((char*)key, (char*)key_buffer[i], 64); /* process keyfile(s) */ if (psalt->nkeyfiles) { apply_keyfiles(key, 64, psalt->nkeyfiles); ksz = 64; } } #if SSE_GROUP_SZ_SHA512 if (psalt->hash_type == IS_SHA512) { int lens[SSE_GROUP_SZ_SHA512]; unsigned char *pin[SSE_GROUP_SZ_SHA512]; union { unsigned char *pout[SSE_GROUP_SZ_SHA512]; unsigned char *poutc; } x; for (j = 0; j < SSE_GROUP_SZ_SHA512; ++j) { lens[j] = strlen((char*)(key_buffer[i+j])); strncpy((char*)Keys[j], (char*)key_buffer[i+j], 64); /* process keyfile(s) */ if (psalt->nkeyfiles) { apply_keyfiles(Keys[j], 64, psalt->nkeyfiles); lens[j] = 64; } pin[j] = key_buffer[i+j]; x.pout[j] = Keys[j]; } pbkdf2_sha512_sse((const unsigned char **)pin, lens, psalt->salt, 64, psalt->num_iterations, &(x.poutc), sizeof(key), 0); } #else if (psalt->hash_type == IS_SHA512) { pbkdf2_sha512((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0); } #endif else if (psalt->hash_type == IS_RIPEMD160 || psalt->hash_type == IS_RIPEMD160BOOT) pbkdf2_ripemd160((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0); else pbkdf2_whirlpool((const unsigned char*)key, ksz, psalt->salt, 64, psalt->num_iterations, key, sizeof(key), 0); for (j = 0; j < psalt->loop_inc; ++j) { #if SSE_GROUP_SZ_SHA512 if (psalt->hash_type == IS_SHA512) memcpy(key, Keys[j], sizeof(key)); #endif cracked[i+j] = 0; if (decrypt_and_verify(key, 0)) // AES cracked[i+j] = 1; else { if (decrypt_and_verify(key, 1)) // Twofish cracked[i+j] = 1; else { if (decrypt_and_verify(key, 2)) // Serpent cracked[i+j] = 1; } } } } return count; } static int cmp_all(void *binary, int count) { int index; for (index = 0; index < count; index++) if (cracked[index]) return 1; return 0; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int idx) { return 1; } static void set_key(char* key, int index) { strcpy((char*)(key_buffer[index]), key); } static char *get_key(int index) { return (char*)(key_buffer[index]); } static int salt_hash(void *salt) { unsigned v=0, i; struct cust_salt *psalt = (struct cust_salt *)salt; for (i = 0; i < 64; ++i) { v *= 11; v += psalt->salt[i]; } return v & (SALT_HASH_SIZE - 1); } static unsigned int tc_hash_algorithm(void *salt) { return (unsigned int)((struct cust_salt*)salt)->hash_type; } struct fmt_main fmt_truecrypt = { { "tc_aes_xts", // FORMAT_LABEL "TrueCrypt AES256_XTS", // FORMAT_NAME #if SSE_GROUP_SZ_SHA512 "SHA512 " SHA512_ALGORITHM_NAME " /RIPEMD160/WHIRLPOOL", #else #if ARCH_BITS >= 64 "SHA512 64/" ARCH_BITS_STR " /RIPEMD160/WHIRLPOOL", #else "SHA512 32/" ARCH_BITS_STR " /RIPEMD160/WHIRLPOOL", #endif #endif "", // BENCHMARK_COMMENT -1, // BENCHMARK_LENGTH 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, #if SSE_GROUP_SZ_SHA512 SSE_GROUP_SZ_SHA512, SSE_GROUP_SZ_SHA512, #else MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #endif FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { "hash algorithm [1:SHA512 2:RIPEMD160 3:Whirlpool]", }, { TAG_WHIRLPOOL, TAG_SHA512, TAG_RIPEMD160 }, tests_all }, { init, done, fmt_default_reset, fmt_default_prepare, valid_truecrypt, fmt_default_split, fmt_default_binary, get_salt, { tc_hash_algorithm, }, fmt_default_source, { fmt_default_binary_hash }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; struct fmt_main fmt_truecrypt_ripemd160 = { { "tc_ripemd160", // FORMAT_LABEL "TrueCrypt AES256_XTS", // FORMAT_NAME "RIPEMD160 32/" ARCH_BITS_STR, // ALGORITHM_NAME, "", // BENCHMARK_COMMENT -1, // 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_HUGE_INPUT, { NULL }, { TAG_RIPEMD160 }, tests_ripemd160 }, { init, done, fmt_default_reset, fmt_default_prepare, valid_ripemd160, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; struct fmt_main fmt_truecrypt_ripemd160boot = { { "tc_ripemd160boot", // FORMAT_LABEL "TrueCrypt AES/Twofish/Serpent", // FORMAT_NAME "RIPEMD160 32/" ARCH_BITS_STR, // ALGORITHM_NAME, "", // BENCHMARK_COMMENT -1, // 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_HUGE_INPUT, { NULL }, { TAG_RIPEMD160BOOT }, tests_ripemd160boot }, { init, done, fmt_default_reset, fmt_default_prepare, valid_ripemd160boot, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; struct fmt_main fmt_truecrypt_sha512 = { { "tc_sha512", // FORMAT_LABEL "TrueCrypt AES256_XTS", // FORMAT_NAME #if SSE_GROUP_SZ_SHA512 "SHA512 " SHA512_ALGORITHM_NAME, // ALGORITHM_NAME, #else #if ARCH_BITS >= 64 "SHA512 64/" ARCH_BITS_STR, #else "SHA512 32/" ARCH_BITS_STR, #endif #endif "", // BENCHMARK_COMMENT -1, // BENCHMARK_LENGTH 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, #if SSE_GROUP_SZ_SHA512 SSE_GROUP_SZ_SHA512, SSE_GROUP_SZ_SHA512, #else MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #endif FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { NULL }, { TAG_SHA512 }, tests_sha512 }, { init, done, fmt_default_reset, fmt_default_prepare, valid_sha512, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; struct fmt_main fmt_truecrypt_whirlpool = { { "tc_whirlpool", // FORMAT_LABEL "TrueCrypt AES256_XTS", // FORMAT_NAME #if ARCH_BITS >= 64 "WHIRLPOOL 64/" ARCH_BITS_STR, // ALGORITHM_NAME, #else "WHIRLPOOL 32/" ARCH_BITS_STR, // ALGORITHM_NAME, #endif "", // BENCHMARK_COMMENT -1, // 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_HUGE_INPUT, { NULL }, { TAG_WHIRLPOOL }, tests_whirlpool }, { init, done, fmt_default_reset, fmt_default_prepare, valid_whirlpool, fmt_default_split, fmt_default_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
sl3_fmt_plug.c
/* * SL3 unlocking. Password is always 15 digits. Run with "-mask=?d" * * Input format (IMEI is put in "login field"): * IMEI:hash * * IMEI is 14 or 15 digits 0-9 (only 14 are used) * hash is hex lowercase (0-9, a-f) * * Copyright (c) 2017 magnum. * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_sl3; #elif FMT_REGISTERS_H john_register_one(&fmt_sl3); #else #include "arch.h" //#undef SIMD_COEF_32 //#undef SIMD_PARA_SHA1 //#undef _OPENMP #include <string.h> #ifdef _OPENMP #ifdef SIMD_COEF_64 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "misc.h" #include "formats.h" #include "options.h" #include "johnswap.h" #ifdef SIMD_COEF_32 #define NBKEYS (SIMD_COEF_32 * SIMD_PARA_SHA1) #endif #include "simd-intrinsics.h" #include "common.h" #include "sha.h" #include "sl3_common.h" #include "base64_convert.h" #include "memdbg.h" #define FORMAT_LABEL "SL3" #define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT NBKEYS #define MAX_KEYS_PER_CRYPT NBKEYS #define GETPOS(i, index) ( (index&(SIMD_COEF_32-1))*4 + ((i)&(0xffffffff-3))*SIMD_COEF_32 + (3-((i)&3)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*4*SIMD_COEF_32 ) //for endianity conversion #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static unsigned char *saved_salt; #ifdef SIMD_COEF_32 static uint32_t (*saved_key)[SHA_BUF_SIZ*NBKEYS]; static uint32_t (*crypt_key)[BINARY_SIZE/4*NBKEYS]; static unsigned int *saved_len; #else static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_key)[BINARY_SIZE / 4]; #endif 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; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifndef SIMD_COEF_32 saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); #else saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); saved_key = mem_calloc_align(self->params.max_keys_per_crypt/NBKEYS, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_key = mem_calloc_align(self->params.max_keys_per_crypt/NBKEYS, sizeof(*crypt_key), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_key); MEM_FREE(saved_key); #ifdef SIMD_COEF_32 MEM_FREE(saved_len); #endif } static void *get_binary(char *ciphertext) { static char *out; if (!out) out = mem_alloc_tiny(BINARY_SIZE, MEM_ALIGN_WORD); ciphertext += SL3_MAGIC_LENGTH + 14 + 1; memset(out, 0, BINARY_SIZE); base64_convert(ciphertext, e_b64_hex, 2 * BINARY_SIZE, out, e_b64_raw, BINARY_SIZE, 0, 0); #ifdef SIMD_COEF_32 alter_endianity((unsigned char*)out, BINARY_SIZE); #endif return (void*)out; } /* set_key() just fills saved_key[index][n] with key[n] - '0' */ static void set_key(char *_key, int index) { #ifdef SIMD_COEF_32 char key[PLAINTEXT_LENGTH + 1]; char *d = key; int i = PLAINTEXT_LENGTH; #if ARCH_ALLOWS_UNALIGNED const uint32_t *wkey = (uint32_t*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint32_t)); const uint32_t *wkey = (uint32_t*)(is_aligned(key, sizeof(uint32_t)) ? key : strcpy(buf_aligned, key)); #endif uint32_t *keybuffer = &((uint32_t*)saved_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32]; uint32_t *keybuf_word = keybuffer; /* * FIXME: Can we do this more efficiently? Perhaps using SIMD and 0x30303030. */ do { *d++ = *_key++ - '0'; } while (i--); *keybuf_word = JOHNSWAP(*wkey++); keybuf_word += SIMD_COEF_32; *keybuf_word = JOHNSWAP(*wkey++); keybuf_word += SIMD_COEF_32; *keybuf_word = JOHNSWAP(*wkey++); keybuf_word += SIMD_COEF_32; *keybuf_word = JOHNSWAP(*wkey); #else char *d = saved_key[index]; int i = PLAINTEXT_LENGTH; do { *d++ = *_key++ - '0'; } while (i--); #endif } /* ...and get_key() reverses the (- '0'). */ static char *get_key(int index) { static char out[PLAINTEXT_LENGTH + 1]; #ifdef SIMD_COEF_32 unsigned int i; for (i = 0; i < PLAINTEXT_LENGTH; i++) out[i] = ((char*)saved_key)[GETPOS(i, index)] + '0'; out[PLAINTEXT_LENGTH] = 0; #else char *s = saved_key[index], *d = out; int i = PLAINTEXT_LENGTH; while (i--) { *d++ = *s++ + '0'; }; *d = 0; #endif return out; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_32 if (((uint32_t*)binary)[0] == ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + index/SIMD_COEF_32*5*SIMD_COEF_32]) #else if ( ((uint32_t*)binary)[0] == ((uint32_t*)&(crypt_key[index][0]))[0] ) #endif return 1; return 0; } static int cmp_exact(char *source, int index) { return 1; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_32 int i; for (i = 0; i < BINARY_SIZE/sizeof(uint32_t); i++) if (((uint32_t*)binary)[i] != ((uint32_t*)crypt_key)[(index&(SIMD_COEF_32-1)) + (unsigned int)index/SIMD_COEF_32*5*SIMD_COEF_32+i*SIMD_COEF_32]) return 0; return 1; #else return !memcmp(binary, crypt_key[index], BINARY_SIZE); #endif } static void set_salt(void *salt) { saved_salt = salt; } #ifdef SIMD_COEF_32 inline static void set_onesalt(int index) { unsigned int i, idx = index % NBKEYS; unsigned char *sk = (unsigned char*)&saved_key[index / NBKEYS]; for (i = 0; i < SALT_SIZE; ++i) sk[GETPOS(PLAINTEXT_LENGTH + i, idx)] = saved_salt[i]; sk[GETPOS(PLAINTEXT_LENGTH + SALT_SIZE, idx)] = 0x80; ((unsigned int*)sk)[15*SIMD_COEF_32 + (index&(SIMD_COEF_32-1)) + idx/SIMD_COEF_32*SHA_BUF_SIZ*SIMD_COEF_32] = (PLAINTEXT_LENGTH + SALT_SIZE) << 3; } #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #ifdef SIMD_COEF_32 int inc = NBKEYS; #else int inc = 1; #endif #pragma omp parallel for for (index=0; index < count; index += inc) #endif { #ifdef SIMD_COEF_32 unsigned int i; for (i=0;i<NBKEYS;i++) set_onesalt(i + index); SIMDSHA1body(saved_key[index/NBKEYS], crypt_key[index/NBKEYS], NULL, SSEi_MIXED_IN); #else SHA_CTX ctx; SHA1_Init( &ctx ); SHA1_Update( &ctx, (unsigned char*)saved_key[index], PLAINTEXT_LENGTH); SHA1_Update( &ctx, (unsigned char*)saved_salt, SALT_SIZE); SHA1_Final( (unsigned char*)crypt_key[index], &ctx); #endif } return count; } #ifdef SIMD_COEF_32 #define HASH_OFFSET (index&(SIMD_COEF_32-1))+(((unsigned int)index%NBKEYS)/SIMD_COEF_32)*SIMD_COEF_32*5 static int get_hash_0(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index/NBKEYS][HASH_OFFSET] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_key[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_key[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_key[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_key[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_key[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_key[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_key[index][0] & PH_MASK_6; } #endif struct fmt_main fmt_sl3 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_MINLEN, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_OMP | FMT_OMP_BAD, { NULL }, { SL3_MAGIC }, sl3_tests }, { init, done, fmt_default_reset, sl3_prepare, sl3_valid, fmt_default_split, get_binary, sl3_get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, sl3_salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
erath1.c
#include "erath/erath1.h" #include <stdlib.h> /* malloc, free */ #include <string.h> /* memset */ #include <math.h> /* ceil, sqrt */ #define CHUNK_WIDTH 19 #include "common/defs.h" #include "common/enum.h" #include "common/presieve.h" #include "common/bitset.h" static inline int erath1_chunk(char* chunk, llong lower, llong upper, const char* sieved) { const llong chunk_size = upper - lower; memset(chunk, 0xFF, CHUNK_BYTES); for (llong p = 2; p*p < upper; ++p) { if (sieved[p] != 0) { llong mod = lower % p; llong i = p * (mod != 0) - mod; for (; i < chunk_size; i += p) { bitset_clear(chunk, i); } } } return 0; } llong erath1(llong lower, llong upper, int print) { llong ret = 0; llong root = ceil(sqrt(upper)); char* arr = (char*)malloc(root * sizeof(char)); if (arr == NULL) { return ret; } enumerate_bitset_precomp(); erath_less_than(arr, root); ret = enumerate(arr + lower, arr + root, lower, print); char* chunk = (char*)malloc(CHUNK_BYTES); if (chunk == NULL) { free(arr); return 0; } bitset_enum_func enumerator = enumerate_bitset; if (print != 0) { enumerator = enumerate_bitset_print; } llong chunk_lower = (root < lower) ? lower : root; llong chunk_upper = chunk_lower + CHUNK_SIZE; for (; chunk_upper < upper; chunk_lower += CHUNK_SIZE, chunk_upper += CHUNK_SIZE) { erath1_chunk(chunk, chunk_lower, chunk_upper, arr); ret += enumerator(chunk, CHUNK_BYTES, chunk_lower); } unsigned last_chunk_bytes = ceil((upper - chunk_lower) / 8.0); erath1_chunk(chunk, chunk_lower, upper, arr); bitset_truncate(chunk, upper - chunk_lower - 1); ret += enumerator(chunk, last_chunk_bytes, chunk_lower); free(chunk); free(arr); return ret; } llong erath1_mt(llong lower, llong upper, int print) { llong ret = 0; llong root = ceil(sqrt(upper)); char* arr = (char*)malloc(root * sizeof(char)); if (arr == NULL) { return ret; } enumerate_bitset_precomp(); erath_less_than(arr, root); ret = enumerate(arr + lower, arr + root, lower, print); bitset_enum_func enumerator = enumerate_bitset; if (print != 0) { enumerator = enumerate_bitset_print; } llong i, first_chunk_start = (root < lower) ? lower : root; #pragma omp parallel for ordered, schedule(dynamic) for (i = first_chunk_start; i < upper; i += CHUNK_SIZE) { char* chunk = (char*)malloc(CHUNK_BYTES); llong chunk_size = CHUNK_SIZE; size_t chunk_bytes = CHUNK_BYTES; if ((i + chunk_size) > upper) { chunk_size = upper - i; chunk_bytes = ceil(chunk_size / 8.0); } erath1_chunk(chunk, i, i + chunk_size, arr); if ((chunk_size & 7) != 0) { bitset_truncate(chunk, chunk_size); } #pragma omp ordered ret += enumerator(chunk, chunk_bytes, i); free(chunk); } free(arr); return ret; }
csr_matvec_oomp.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE 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) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ //#if defined(HYPRE_USING_UNIFIED_MEMORY) #include "seq_mv.h" #include <assert.h> #define NUM_TEAMS 2048 #define NUM_THREADS 1024 /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec *--------------------------------------------------------------------------*/ /* y[offset:end] = alpha*A[offset:end,:]*x + beta*b[offset:end] */ HYPRE_Int hypre_CSRMatrixMatvecOutOfPlaceOOMP2( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ) { /* printf("CALLING OOOMP MATVE\n"); */ #ifdef HYPRE_PROFILE HYPRE_Real time_begin = hypre_MPI_Wtime(); #endif #if defined(HYPRE_USING_GPU) && defined(HYPRE_USING_UNIFIED_MEMORY) PUSH_RANGE_PAYLOAD("MATVEC_OOMP",0, hypre_CSRMatrixNumRows(A)); HYPRE_Int ierr = hypre_CSRMatrixMatvecDevice( alpha,A,x,beta,b,y,offset ); POP_RANGE; #else HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset; HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset; HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); /*HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A);*/ HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A); HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A); HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *b_data = hypre_VectorData(b) + offset; HYPRE_Complex *y_data = hypre_VectorData(y) + offset; HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int b_size = hypre_VectorSize(b) - offset; HYPRE_Int y_size = hypre_VectorSize(y) - offset; HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); /*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b); HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/ HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Complex temp, tempx; HYPRE_Int i, j, jj; HYPRE_Int m; HYPRE_Real xpar=0.7; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); hypre_assert( num_vectors == hypre_VectorNumVectors(b) ); if (num_cols != x_size) ierr = 1; if (num_rows != y_size || num_rows != b_size) ierr = 2; if (num_cols != x_size && (num_rows != y_size || num_rows != b_size)) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { if (y_data!=b_data){ #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 0\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,b_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = beta*b_data[i]; } else { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 1\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= beta; } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } if (x == y) { x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; /* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller than num_rows */ if (num_rownnz < xpar*(num_rows) || num_vectors > 1) { /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 2\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = 0.0; } else { if (y_data!=b_data){ #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 3\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,b_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]*temp; } else { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 4\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = y_data[i]*temp; } } } else { if (y_data!=b_data){ #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 5\n"); #pragma omp target teams distribute parallel for num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = b_data[i]; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ if (num_rownnz < xpar*(num_rows)) { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 6\n"); #pragma omp target teams distribute parallel for private(i,j,jj,m,tempx) num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,A_data,x_data,A_i,A_j) #endif for (i = 0; i < num_rownnz; i++) { m = A_rownnz[i]; /* * for (jj = A_i[m]; jj < A_i[m+1]; jj++) * { * j = A_j[jj]; * y_data[m] += A_data[jj] * x_data[j]; * } */ if ( num_vectors==1 ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[A_j[jj]]; y_data[m] += tempx; } else for ( j=0; j<num_vectors; ++j ) { tempx = 0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; y_data[ j*vecstride_y + m*idxstride_y] += tempx; } } } else // num_vectors > 1 { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Sub loop 7\n"); #pragma omp target teams distribute parallel for private(i,j,jj,m,tempx) num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,A_data,x_data,A_i,A_j) #endif for (i = 0; i < num_rows; i++) { for (j = 0; j < num_vectors; ++j) { tempx = 0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; } y_data[ j*vecstride_y + i*idxstride_y ] += tempx; } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Alph!=1 loop 0\n"); #pragma omp target teams distribute parallel for private(i) num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data) #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= alpha; // WHAT is going on here ? } } else { // JSP: this is currently the only path optimized if (y_data!=b_data){ #ifdef HYPRE_USING_OPENMP_OFFLOAD //printf("Main work loop 1\n"); #pragma omp target teams distribute parallel for private(i,j,jj,m,tempx) num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,A_data,x_data,A_i,A_j) #endif for(i=0;i<num_rows;i++) { y_data[i]=beta*b_data[i]; HYPRE_Complex temp = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] += alpha*temp; //y_data[i] *= alpha; } } else { /*printf("Main work loop 2 %d offset = %d alpha =%lf beta = %lf \n",num_rows,offset,alpha,beta);*/ #ifdef HYPRE_USING_OPENMP_OFFLOAD22 #pragma omp target teams distribute parallel for private(i,j,jj,tempx) num_teams(NUM_TEAMS) thread_limit(NUM_THREADS) is_device_ptr(y_data,A_data,x_data,A_i,A_j) #endif for(i=0;i<num_rows;i++) { //y_data[i]=beta*y_data[i]; HYPRE_Complex tempx = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) tempx += A_data[jj] * x_data[A_j[jj]]; y_data[i] = alpha*tempx+beta*y_data[i]; //y_data[i] *= alpha; } } } if (x == y) hypre_SeqVectorDestroy(x_tmp); #endif /* defined(HYPRE_USING_GPU) && defined(HYPRE_USING_UNIFIED_MEMORY) */ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif return ierr; } HYPRE_Int hypre_CSRMatrixMatvecOutOfPlaceOOMP( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ) { #ifdef HYPRE_PROFILE HYPRE_Real time_begin = hypre_MPI_Wtime(); #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_MATVEC] += hypre_MPI_Wtime() - time_begin; #endif HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A) + offset; HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A) - offset; #ifdef HYPRE_USING_CUSPARSE HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nnz = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A); HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int b_size = hypre_VectorSize(b) - offset; HYPRE_Int y_size = hypre_VectorSize(y) - offset; HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); /*HYPRE_Int idxstride_b = hypre_VectorIndexStride(b); HYPRE_Int vecstride_b = hypre_VectorVectorStride(b);*/ HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); HYPRE_Real xpar=0.7; #endif HYPRE_Complex *x_data = hypre_VectorData(x); HYPRE_Complex *b_data = hypre_VectorData(b) + offset; HYPRE_Complex *y_data = hypre_VectorData(y) + offset; HYPRE_Int ierr = 0; hypre_Vector *x_tmp = NULL; if (offset!=0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"WARNING :: NON ZERO OFFSET\n OPENMP version with no-zero offset not tested\n"); return hypre_error_flag; } #ifdef HYPRE_USING_CUSPARSE static cusparseHandle_t handle; static cusparseMatDescr_t descr; static HYPRE_Int FirstCall=1; cusparseStatus_t status; static cudaStream_t s[10]; static HYPRE_Int myid; if (FirstCall){ PUSH_RANGE("FIRST_CALL",4); handle=getCusparseHandle(); status= cusparseCreateMatDescr(&descr); if (status != CUSPARSE_STATUS_SUCCESS) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"ERROR:: Matrix descriptor initialization failed\n"); return hypre_error_flag; } cusparseSetMatType(descr,CUSPARSE_MATRIX_TYPE_GENERAL); cusparseSetMatIndexBase(descr,CUSPARSE_INDEX_BASE_ZERO); FirstCall=0; hypre_int jj; for(jj=0;jj<5;jj++) s[jj]=HYPRE_STREAM(jj); nvtxNameCudaStreamA(s[4], "HYPRE_COMPUTE_STREAM"); hypre_MPI_Comm_rank(hypre_MPI_COMM_WORLD, &myid ); myid++; POP_RANGE; } #endif #ifdef HYPRE_USING_UNIFIED_MEMORY hypre_CSRMatrixPrefetchToDevice(A); hypre_SeqVectorPrefetchToDevice(x); hypre_SeqVectorPrefetchToDevice(y); if (b!=y) hypre_SeqVectorPrefetchToDevice(b); #endif #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD if (A->mapped==-1) { //hypre_CSRMatrixSortHost(A); hypre_CSRMatrixMapToDevice(A); //printf("MAPPING %p \n",A); hypre_CSRMatrixUpdateToDevice(A); //printf("DONE MAPPING %p \n",A); } //printf("Mapping X::"); if (!x->mapped) hypre_SeqVectorMapToDevice(x); else SyncVectorToDevice(x); //printf("Mapping Y::"); if (!y->mapped) hypre_SeqVectorMapToDevice(y); else SyncVectorToDevice(y); if (b!=y){ if(!b->mapped) { //printf("Mapping B::"); hypre_SeqVectorMapToDevice(b); } else SyncVectorToDevice(b); } #endif if (x == y) { #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD hypre_error_w_msg(HYPRE_ERROR_GENERIC,"WARNING:: x_tmp is not mapped in Mapped OMP Offload version\n"); #endif x_tmp = hypre_SeqVectorCloneDeep(x); x_data = hypre_VectorData(x_tmp); } HYPRE_Int i; #ifdef HYPRE_USING_CUSPARSE #if defined(TRACK_MEMORY_ALLOCATIONS) ASSERT_MANAGED(A_data); ASSERT_MANAGED(A_i); ASSERT_MANAGED(A_j); ASSERT_MANAGED(x_data); ASSERT_MANAGED(y_data); ASSERT_MANAGED(b_data); #endif if (b!=y){ #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD #pragma omp target teams distribute parallel for private(i) #else #pragma omp target teams distribute parallel for private(i) is_device_ptr(y_data,b_data) #endif for(i=0;i<y_size;i++) y_data[i] = b_data[i]; } if (A->num_rows>0){ #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD #pragma omp target data use_device_ptr(A_data,x_data,y_data,A_i,A_j) #endif cusparseErrchk(cusparseDcsrmv(handle , CUSPARSE_OPERATION_NON_TRANSPOSE, num_rows, num_cols, num_nnz, &alpha, descr, A_data ,A_i,A_j, x_data, &beta, y_data)); } hypre_CheckErrorDevice(cudaStreamSynchronize(s[4])); #else #ifdef HYPRE_USING_OPENMP_OFFLOAD HYPRE_Int num_threads=64; // >64 for 100% Theoritical occupancy HYPRE_Int num_teams = (num_rows+num_rows%num_threads)/num_threads; #pragma omp target teams distribute parallel for private(i) num_teams(num_teams) thread_limit(num_threads) is_device_ptr(A_data,A_i,A_j,y_data,b_data,x_data) schedule(static,1) #endif #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD HYPRE_Int num_threads=64; // >64 for 100% Theoritical occupancy HYPRE_Int num_teams = (num_rows+num_rows%num_threads)/num_threads; // printf("Matvec with %d teams & %d tehreads \n",num_teams,num_threads); // printf("Mapping map %d %d %d %d\n",omp_target_is_present(A,0),omp_target_is_present(A_data,0),omp_target_is_present(A_i,0),omp_target_is_present(A_j,0)); #pragma omp target teams distribute parallel for private(i) num_teams(num_teams) thread_limit(num_threads) schedule(static,1) #endif for(i=0;i<num_rows;i++) { HYPRE_Complex tempx = 0.0; HYPRE_Int jj; for (jj = A_i[i]; jj < A_i[i+1]; jj++){ tempx += A_data[jj] * x_data[A_j[jj]]; } y_data[i] = alpha*tempx+beta*b_data[i]; } #endif #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD UpdateDRC(y); #endif if (x == y) hypre_SeqVectorDestroy(x_tmp); //printRC(y,"Inside MatvecOOMP"); //hypre_SeqVectorUpdateHost(y); #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD //hypre_SeqVectorUnMapFromDevice(y); //hypre_SeqVectorUnMapFromDevice(x); //if ((b!=y)&&(b->mapped)) hypre_SeqVectorUnMapFromDevice(b); #endif //printf("DONE WITH OOMP\n"); return ierr; } HYPRE_Int hypre_CSRMatrixMatvecOutOfPlaceOOMP3( HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Vector *x, HYPRE_Complex beta, hypre_Vector *b, hypre_Vector *y, HYPRE_Int offset ) { return 0; /* hypre_CSRMatrixMatvecOutOfPlaceOOMP(alpha,A,x,beta,b,y,offset); #ifdef HYPRE_USING_MAPPED_OPENMP_OFFLOAD hypre_SeqVectorUpdateHost(y); #endif return 0; */ } /* HYPRE_Int hypre_CSRMatrixSortHost(hypre_CSRMatrix *A){ */ /* HYPRE_Int ierr=0; */ /* HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); */ /* HYPRE_Int *A_i = hypre_CSRMatrixI(A); */ /* HYPRE_Int *A_j = hypre_CSRMatrixJ(A); */ /* HYPRE_Complex *A_data=hypre_CSRMatrixData(A); */ /* HYPRE_Int i, j; */ /* //printf("hypre_CSRMatrixSortHost\n"); */ /* for (i=0; i < num_rows; i++){ */ /* //printf("Row %d size %d \n",i,(A_i[i+1]-A_i[i])); */ /* mysort(&A_data[A_i[i]],&A_j[A_i[i]],(A_i[i+1]-A_i[i])); */ /* } */ /* } */ //#endif
3d7pt.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 * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 16; tile_size[3] = 2048; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; const double alpha = 0.0876; const double beta = 0.0765; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* 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,4);t1++) { lbp=max(ceild(t1,2),ceild(8*t1-Nt+3,8)); ubp=min(floord(Nt+Nz-4,8),floord(4*t1+Nz+1,8)); #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-3,4)),ceild(8*t2-Nz-12,16));t3<=min(min(min(floord(Nt+Ny-4,16),floord(4*t1+Ny+5,16)),floord(8*t2+Ny+4,16)),floord(8*t1-8*t2+Nz+Ny+3,16));t3++) { for (t4=max(max(max(0,ceild(t1-511,512)),ceild(8*t2-Nz-2044,2048)),ceild(16*t3-Ny-2044,2048));t4<=min(min(min(min(floord(Nt+Nx-4,2048),floord(4*t1+Nx+5,2048)),floord(8*t2+Nx+4,2048)),floord(16*t3+Nx+12,2048)),floord(8*t1-8*t2+Nz+Nx+3,2048));t4++) { for (t5=max(max(max(max(max(0,4*t1),8*t1-8*t2+1),8*t2-Nz+2),16*t3-Ny+2),2048*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,4*t1+7),8*t2+6),16*t3+14),2048*t4+2046),8*t1-8*t2+Nz+5);t5++) { for (t6=max(max(8*t2,t5+1),-8*t1+8*t2+2*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+2*t5),t5+Nz-2);t6++) { for (t7=max(16*t3,t5+1);t7<=min(16*t3+15,t5+Ny-2);t7++) { lbv=max(2048*t4,t5+1); ubv=min(2048*t4+2047,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = ((alpha * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (beta * (((((A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)] + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1]) + A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)]) + A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-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, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays (Causing performance degradation /* for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); */ return 0; }
prettyfunc.c
// Test the handling of pretty function // There should be a hidden variable declaration inserted under the closest enclosing scope // Liao 2013-1-10 int main() { // int i=100,sum=0; #pragma omp parallel { __PRETTY_FUNCTION__; } return 0; }
omptarget.h
//===---- omptarget.h - OpenMP GPU initialization ---------------- CUDA -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains the declarations of all library macros, types, // and functions. // //===----------------------------------------------------------------------===// #ifndef OMPTARGET_H #define OMPTARGET_H #include "common/allocator.h" #include "common/debug.h" // debug #include "common/state-queue.h" #include "common/support.h" #include "interface.h" // interfaces with omp, compiler, and user #include "target_impl.h" #define OMPTARGET_NVPTX_VERSION 1.1 // used by the library for the interface with the app #define DISPATCH_FINISHED 0 #define DISPATCH_NOTFINISHED 1 // used by dynamic scheduling #define FINISHED 0 #define NOT_FINISHED 1 #define LAST_CHUNK 2 #define BARRIER_COUNTER 0 #define ORDERED_COUNTER 1 // Worker slot type which is initialized with the default worker slot // size of 4*32 bytes. struct __kmpc_data_sharing_slot { __kmpc_data_sharing_slot *Next; __kmpc_data_sharing_slot *Prev; void *PrevSlotStackPtr; void *DataEnd; char Data[DS_Worker_Warp_Slot_Size]; }; //////////////////////////////////////////////////////////////////////////////// // task ICV and (implicit & explicit) task state class omptarget_nvptx_TaskDescr { public: // methods for flags INLINE omp_sched_t GetRuntimeSched() const; INLINE void SetRuntimeSched(omp_sched_t sched); INLINE int InParallelRegion() const { return items.flags & TaskDescr_InPar; } INLINE int InL2OrHigherParallelRegion() const { return items.flags & TaskDescr_InParL2P; } INLINE int IsParallelConstruct() const { return items.flags & TaskDescr_IsParConstr; } INLINE int IsTaskConstruct() const { return !IsParallelConstruct(); } // methods for other fields INLINE uint16_t &ThreadId() { return items.threadId; } INLINE uint64_t &RuntimeChunkSize() { return items.runtimeChunkSize; } INLINE omptarget_nvptx_TaskDescr *GetPrevTaskDescr() const { return prev; } INLINE void SetPrevTaskDescr(omptarget_nvptx_TaskDescr *taskDescr) { prev = taskDescr; } // init & copy INLINE void InitLevelZeroTaskDescr(); INLINE void InitLevelOneTaskDescr(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void Copy(omptarget_nvptx_TaskDescr *sourceTaskDescr); INLINE void CopyData(omptarget_nvptx_TaskDescr *sourceTaskDescr); INLINE void CopyParent(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void CopyForExplicitTask(omptarget_nvptx_TaskDescr *parentTaskDescr); INLINE void CopyToWorkDescr(omptarget_nvptx_TaskDescr *masterTaskDescr); INLINE void CopyFromWorkDescr(omptarget_nvptx_TaskDescr *workTaskDescr); INLINE void CopyConvergentParent(omptarget_nvptx_TaskDescr *parentTaskDescr, uint16_t tid, uint16_t tnum); INLINE void SaveLoopData(); INLINE void RestoreLoopData() const; private: // bits for flags: (6 used, 2 free) // 3 bits (SchedMask) for runtime schedule // 1 bit (InPar) if this thread has encountered one or more parallel region // 1 bit (IsParConstr) if ICV for a parallel region (false = explicit task) // 1 bit (InParL2+) if this thread has encountered L2 or higher parallel // region static const uint8_t TaskDescr_SchedMask = (0x1 | 0x2 | 0x4); static const uint8_t TaskDescr_InPar = 0x10; static const uint8_t TaskDescr_IsParConstr = 0x20; static const uint8_t TaskDescr_InParL2P = 0x40; struct SavedLoopDescr_items { int64_t loopUpperBound; int64_t nextLowerBound; int64_t chunk; int64_t stride; kmp_sched_t schedule; } loopData; struct TaskDescr_items { uint8_t flags; // 6 bit used (see flag above) uint8_t unused; uint16_t threadId; // thread id uint64_t runtimeChunkSize; // runtime chunk size } items; omptarget_nvptx_TaskDescr *prev; }; // build on kmp typedef struct omptarget_nvptx_ExplicitTaskDescr { omptarget_nvptx_TaskDescr taskDescr; // omptarget_nvptx task description (must be first) kmp_TaskDescr kmpTaskDescr; // kmp task description (must be last) } omptarget_nvptx_ExplicitTaskDescr; //////////////////////////////////////////////////////////////////////////////// // Descriptor of a parallel region (worksharing in general) class omptarget_nvptx_WorkDescr { public: // access to data INLINE omptarget_nvptx_TaskDescr *WorkTaskDescr() { return &masterTaskICV; } private: omptarget_nvptx_TaskDescr masterTaskICV; }; //////////////////////////////////////////////////////////////////////////////// class omptarget_nvptx_TeamDescr { public: // access to data INLINE omptarget_nvptx_TaskDescr *LevelZeroTaskDescr() { return &levelZeroTaskDescr; } INLINE omptarget_nvptx_WorkDescr &WorkDescr() { return workDescrForActiveParallel; } // init INLINE void InitTeamDescr(); INLINE __kmpc_data_sharing_slot *GetPreallocatedSlotAddr(int wid) { worker_rootS[wid].DataEnd = &worker_rootS[wid].Data[0] + DS_Worker_Warp_Slot_Size; // We currently do not have a next slot. worker_rootS[wid].Next = 0; worker_rootS[wid].Prev = 0; worker_rootS[wid].PrevSlotStackPtr = 0; return (__kmpc_data_sharing_slot *)&worker_rootS[wid]; } private: omptarget_nvptx_TaskDescr levelZeroTaskDescr; // icv for team master initial thread omptarget_nvptx_WorkDescr workDescrForActiveParallel; // one, ONLY for the active par ALIGN(16) __kmpc_data_sharing_slot worker_rootS[DS_Max_Warp_Number]; }; //////////////////////////////////////////////////////////////////////////////// // thread private data (struct of arrays for better coalescing) // tid refers here to the global thread id // do not support multiple concurrent kernel a this time class omptarget_nvptx_ThreadPrivateContext { public: // task INLINE omptarget_nvptx_TaskDescr *Level1TaskDescr(int tid) { return &levelOneTaskDescr[tid]; } INLINE void SetTopLevelTaskDescr(int tid, omptarget_nvptx_TaskDescr *taskICV) { topTaskDescr[tid] = taskICV; } INLINE omptarget_nvptx_TaskDescr *GetTopLevelTaskDescr(int tid) const; // parallel INLINE uint16_t &NumThreadsForNextParallel(int tid) { return nextRegion.tnum[tid]; } // schedule (for dispatch) INLINE kmp_sched_t &ScheduleType(int tid) { return schedule[tid]; } INLINE int64_t &Chunk(int tid) { return chunk[tid]; } INLINE int64_t &LoopUpperBound(int tid) { return loopUpperBound[tid]; } INLINE int64_t &NextLowerBound(int tid) { return nextLowerBound[tid]; } INLINE int64_t &Stride(int tid) { return stride[tid]; } INLINE omptarget_nvptx_TeamDescr &TeamContext() { return teamContext; } INLINE void InitThreadPrivateContext(int tid); INLINE uint64_t &Cnt() { return cnt; } private: // team context for this team omptarget_nvptx_TeamDescr teamContext; // task ICV for implicit threads in the only parallel region omptarget_nvptx_TaskDescr levelOneTaskDescr[MAX_THREADS_PER_TEAM]; // pointer where to find the current task ICV (top of the stack) omptarget_nvptx_TaskDescr *topTaskDescr[MAX_THREADS_PER_TEAM]; union { // Only one of the two is live at the same time. // parallel uint16_t tnum[MAX_THREADS_PER_TEAM]; } nextRegion; // schedule (for dispatch) kmp_sched_t schedule[MAX_THREADS_PER_TEAM]; // remember schedule type for #for int64_t chunk[MAX_THREADS_PER_TEAM]; int64_t loopUpperBound[MAX_THREADS_PER_TEAM]; // state for dispatch with dyn/guided OR static (never use both at a time) int64_t nextLowerBound[MAX_THREADS_PER_TEAM]; int64_t stride[MAX_THREADS_PER_TEAM]; uint64_t cnt; }; /// Memory manager for statically allocated memory. class omptarget_nvptx_SimpleMemoryManager { private: struct MemDataTy { volatile unsigned keys[OMP_STATE_COUNT]; } MemData[MAX_SM] ALIGN(128); INLINE static uint32_t hash(unsigned key) { return key & (OMP_STATE_COUNT - 1); } public: INLINE void Release(); INLINE const void *Acquire(const void *buf, size_t size); }; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // global data tables //////////////////////////////////////////////////////////////////////////////// extern omptarget_nvptx_SimpleMemoryManager omptarget_nvptx_simpleMemoryManager; extern uint32_t EXTERN_SHARED(usedMemIdx); extern uint32_t EXTERN_SHARED(usedSlotIdx); #if _OPENMP extern uint8_t parallelLevel[MAX_THREADS_PER_TEAM / WARPSIZE]; #pragma omp allocate(parallelLevel) allocator(omp_pteam_mem_alloc) #else extern uint8_t EXTERN_SHARED(parallelLevel)[MAX_THREADS_PER_TEAM / WARPSIZE]; #endif extern uint16_t EXTERN_SHARED(threadLimit); extern uint16_t EXTERN_SHARED(threadsInTeam); extern uint16_t EXTERN_SHARED(nThreads); extern omptarget_nvptx_ThreadPrivateContext * EXTERN_SHARED(omptarget_nvptx_threadPrivateContext); extern int8_t EXTERN_SHARED(execution_param); extern void *EXTERN_SHARED(ReductionScratchpadPtr); //////////////////////////////////////////////////////////////////////////////// // work function (outlined parallel/simd functions) and arguments. // needed for L1 parallelism only. //////////////////////////////////////////////////////////////////////////////// typedef void *omptarget_nvptx_WorkFn; extern omptarget_nvptx_WorkFn EXTERN_SHARED(omptarget_nvptx_workFn); //////////////////////////////////////////////////////////////////////////////// // get private data structures //////////////////////////////////////////////////////////////////////////////// INLINE omptarget_nvptx_TeamDescr &getMyTeamDescriptor(); INLINE omptarget_nvptx_WorkDescr &getMyWorkDescriptor(); INLINE omptarget_nvptx_TaskDescr * getMyTopTaskDescriptor(bool isSPMDExecutionMode); INLINE omptarget_nvptx_TaskDescr *getMyTopTaskDescriptor(int globalThreadId); //////////////////////////////////////////////////////////////////////////////// // inlined implementation //////////////////////////////////////////////////////////////////////////////// INLINE uint32_t __kmpc_impl_ffs(uint32_t x) { return __builtin_ffs(x); } INLINE uint32_t __kmpc_impl_popc(uint32_t x) { return __builtin_popcount(x); } INLINE uint32_t __kmpc_impl_ffs(uint64_t x) { return __builtin_ffsl(x); } INLINE uint32_t __kmpc_impl_popc(uint64_t x) { return __builtin_popcountl(x); } #include "common/omptargeti.h" #endif
pbkdf2-hmac-md4_fmt_plug.c
/* * This software is Copyright (c) 2015 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. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_pbkdf2_hmac_md4; #elif FMT_REGISTERS_H john_register_one(&fmt_pbkdf2_hmac_md4); #else #include <ctype.h> #include <string.h> #include <assert.h> #include <stdint.h> #include "arch.h" //#undef SIMD_COEF_32 #include "misc.h" #include "common.h" #include "formats.h" #include "pbkdf2_hmac_md4.h" #include "pbkdf2_hmac_common.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 256 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "PBKDF2-HMAC-MD4" #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-MD4 " MD4_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-MD4 32/" ARCH_BITS_STR #endif #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(uint32_t) #if SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_32 * SIMD_PARA_MD4) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_32 * SIMD_PARA_MD4) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define PLAINTEXT_LENGTH 125 static struct custom_salt { unsigned int length; unsigned int rounds; char salt[PBKDF2_32_MAX_SALT_SIZE]; } *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[PBKDF2_MDx_BINARY_SIZE / sizeof(uint32_t)]; 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_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static void *get_salt(char *ciphertext) { static struct custom_salt cs; char *p; int saltlen; char delim; if (!strncmp(ciphertext, PBKDF2_MD4_FORMAT_TAG, sizeof(PBKDF2_MD4_FORMAT_TAG) - 1)) ciphertext += sizeof(PBKDF2_MD4_FORMAT_TAG) - 1; memset(&cs, 0, sizeof(cs)); cs.rounds = atoi(ciphertext); delim = strchr(ciphertext, '.') ? '.' : '$'; ciphertext = strchr(ciphertext, delim) + 1; p = strchr(ciphertext, delim); saltlen = 0; memset(cs.salt, 0, sizeof(cs.salt)); while (ciphertext < p) { /** extract salt **/ cs.salt[saltlen++] = atoi16[ARCH_INDEX(ciphertext[0])] * 16 + atoi16[ARCH_INDEX(ciphertext[1])]; ciphertext += 2; } cs.length = saltlen; return (void*)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) { #if SIMD_COEF_32 int lens[SSE_GROUP_SZ_MD4], i; unsigned char *pin[SSE_GROUP_SZ_MD4]; union { uint32_t *pout[SSE_GROUP_SZ_MD4]; unsigned char *poutc; } x; for (i = 0; i < SSE_GROUP_SZ_MD4; ++i) { lens[i] = strlen(saved_key[index+i]); pin[i] = (unsigned char*)saved_key[index+i]; x.pout[i] = crypt_out[index+i]; } pbkdf2_md4_sse((const unsigned char **)pin, lens, (unsigned char*)cur_salt->salt, cur_salt->length, cur_salt->rounds, &(x.poutc), PBKDF2_MDx_BINARY_SIZE, 0); #else pbkdf2_md4((unsigned char*)(saved_key[index]), strlen(saved_key[index]), (unsigned char*)cur_salt->salt, cur_salt->length, cur_salt->rounds, (unsigned char*)crypt_out[index], PBKDF2_MDx_BINARY_SIZE, 0); #endif } return count; } static int cmp_all(void *binary, int count) { int index = 0; #if defined(_OPENMP) || MAX_KEYS_PER_CRYPT > 1 for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; //dump_stuff_msg("\nbinary", crypt_out[count - 1], 16); return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], PBKDF2_MDx_BINARY_SIZE); } static void set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static int cmp_exact(char *source, int index) { /* does a FULL compare, if the binary buffer of the hash is larger than 16 bytes */ return pbkdf2_hmac_md4_cmp_exact(get_key(index), source, (unsigned char*)cur_salt->salt, cur_salt->length, cur_salt->rounds); } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->rounds; } struct fmt_main fmt_pbkdf2_hmac_md4 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, PBKDF2_MDx_BINARY_SIZE, PBKDF2_32_BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, { PBKDF2_MD4_FORMAT_TAG }, pbkdf2_hmac_md4_common_tests }, { init, done, fmt_default_reset, fmt_default_prepare, pbkdf2_hmac_md4_valid, pbkdf2_hmac_md4_split, pbkdf2_hmac_md4_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, set_salt, 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 */
lchol_csc_executor.h
// // Created by kazem on 11/14/18. // #ifndef PROJECT_HLEVEL_SIMPLICIAL_CHOLESKY_H #define PROJECT_HLEVEL_SIMPLICIAL_CHOLESKY_H #include <stdlib.h> #include <cmath> #include "omp.h" bool lchol_csc_executor(int n, int* c, int* r, double* values, size_t* lC, MKL_INT* lR, double* &lValues, int *prunePtr, int *pruneSet, int nLevels, int *levelPtr, int *levelSet, int nPar, int *parPtr, int *partition, int chunk) { /* * Performs a Cholesky decomposition on a given matrix (c, r, values), i.e. * stored in compressed column format, and produces L, which are * stored in column compressed format. * (n, c, r, values) : IN : input matrix * (lC, lR) : IN : The column and rwo sparsity patterns of L * (lValues) : OUT : the nonzero values of the L factor * (pruneSet, prunePtr) : IN : the row sparsity pattern of the factor L */ double *f ;//= new double[n](); //for (int colNo = 0; colNo < n; ++colNo) { omp_set_nested(1); for (int i1 = 0; i1 < nLevels; ++i1) { #pragma omp parallel private(f) { #pragma omp for schedule(auto) private(f) for (int j1 = levelPtr[i1]; j1 < levelPtr[i1 + 1]; ++j1) { f = new double[n](); //int pls = levelSet[j1]; for (int k1 = parPtr[j1]; k1 < parPtr[j1 + 1]; ++k1) { int colNo = partition[k1]; assert(colNo < n); //Uncompressing a col into a 1D array for (int nzNo = c[colNo]; nzNo < c[colNo + 1]; ++nzNo) { f[r[nzNo]] = values[nzNo];//Copying nonzero of the col } for (int i = prunePtr[colNo]; i < prunePtr[colNo + 1]; ++i) { double tmp = 0; int spCol = pruneSet[i]; bool sw = false; for (int l = lC[spCol]; l < lC[spCol + 1]; ++l) { if (lR[l] == colNo && !sw) { tmp = lValues[l]; sw = true; } if (sw) { f[lR[l]] -= lValues[l] * tmp; } } } assert(f[colNo] > 0); if (f[colNo] <= 0) exit(-1); //The matrix is not SPD double tmpSqrt = sqrt(f[colNo]); f[colNo] = 0; lValues[lC[colNo]] = tmpSqrt; for (int j = lC[colNo] + 1; j < lC[colNo + 1]; ++j) { lValues[j] = f[lR[j]] / tmpSqrt; f[lR[j]] = 0; } } delete[]f; } } } return true; } #endif //PROJECT_HLEVEL_SIMPLICIAL_CHOLESKY_H
parallel.c
#include "parallel.h" #include <stdlib.h> #include <math.h> #include <assert.h> #if TCI_USE_OPENMP_THREADS int tci_parallelize(tci_thread_func func, void* payload, unsigned nthread, unsigned arity) { if (nthread <= 1) { func(tci_single, payload); return 0; } tci_context* context; int ret = tci_context_init(&context, nthread, arity); if (ret != 0) return ret; #pragma omp parallel num_threads(nthread) { tci_comm comm; tci_comm_init(&comm, context, nthread, (unsigned)omp_get_thread_num(), 1, 0); func(&comm, payload); #pragma omp barrier tci_comm_destroy(&comm); } return 0; } #elif TCI_USE_OMPTASK_THREADS int tci_parallelize(tci_thread_func func, void* payload, unsigned nthread, unsigned arity) { #pragma omp parallel num_threads(nthread) { #pragma omp single func(tci_single, payload); } return 0; } #elif TCI_USE_PTHREADS_THREADS typedef struct { tci_thread_func func; void* payload; tci_context* context; unsigned nthread, tid; } tci_thread_data; void* tci_run_thread(void* raw_data) { tci_thread_data* data = (tci_thread_data*)raw_data; tci_comm comm; tci_comm_init(&comm, data->context, data->nthread, data->tid, 1, 0); data->func(&comm, data->payload); tci_comm_destroy(&comm); return NULL; } int tci_parallelize(tci_thread_func func, void* payload, unsigned nthread, unsigned arity) { if (nthread <= 1) { func(tci_single, payload); return 0; } tci_context* context; int ret = tci_context_init(&context, nthread, arity); if (ret != 0) return ret; pthread_t threads[nthread]; tci_thread_data data[nthread]; tci_comm comm0; tci_comm_init(&comm0, context, nthread, 0, 1, 0); for (unsigned i = 1;i < nthread;i++) { data[i].func = func; data[i].payload = payload; data[i].context = context; data[i].nthread = nthread; data[i].tid = i; int ret = pthread_create(&threads[i], NULL, tci_run_thread, &data[i]); if (ret != 0) { for (unsigned j = 1;j < i;j++) pthread_join(threads[j], NULL); return ret; } } func(&comm0, payload); for (unsigned i = 1;i < nthread;i++) { pthread_join(threads[i], NULL); } return tci_comm_destroy(&comm0); } #elif TCI_USE_WINDOWS_THREADS //TODO typedef struct { tci_thread_func func; void* payload; tci_context* context; unsigned nthread, tid; } tci_thread_data; DWORD WINAPI tci_run_thread(void* raw_data) { tci_thread_data* data = (tci_thread_data*)raw_data; tci_comm comm; tci_comm_init(&comm, data->context, data->nthread, data->tid, 1, 0); data->func(&comm, data->payload); tci_comm_destroy(&comm); return NULL; } int tci_parallelize(tci_thread_func func, void* payload, unsigned nthread, unsigned arity) { if (nthread <= 1) { func(tci_single, payload); return 0; } tci_context* context; int ret = tci_context_init(&context, nthread, arity); if (ret != 0) return ret; HANDLE threads[nthread-1]; tci_thread_data data[nthread-1]; for (unsigned i = 0;i < nthread-1;i++) { data[i].func = func; data[i].payload = payload; data[i].context = context; data[i].nthread = nthread; data[i].tid = i+1; threads[i] = CreateThread(NULL, 0, tci_run_thread, &data[i], 0, NULL); if (!threads[i]) { WaitForMultipleObjects(i, threads, TRUE, INFINITE); return -1; } } tci_comm comm0; tci_comm_init(&comm0, context, nthread, 0, 1, 0); func(&comm0, payload); WaitForMultipleObjects(nthread-1, threads, TRUE, INFINITE); return tci_comm_destroy(&comm0); } #else // TCI_USE_TBB_THREADS, TCI_USE_DISPATCH_THREADS, // TCI_USE_PPL_THREADS, single threaded int tci_parallelize(tci_thread_func func, void* payload, unsigned nthread, unsigned arity) { tci_comm comm = {NULL, 1, 0, nthread, 0}; func(&comm, payload); return 0; } #endif void tci_prime_factorization(unsigned n, tci_prime_factors* factors) { factors->n = n; // all this is necessary to appease the warning gods factors->sqrt_n = (unsigned)lrint(floor(sqrt(n))); factors->f = 2; } unsigned tci_next_prime_factor(tci_prime_factors* factors) { for (;factors->f <= factors->sqrt_n;) { if (factors->f == 2) { if (factors->n%2 == 0) { factors->n /= 2; return 2; } factors->f = 3; } else if (factors->f == 3) { if (factors->n%3 == 0) { factors->n /= 3; return 3; } factors->f = 5; } else if (factors->f == 5) { if (factors->n%5 == 0) { factors->n /= 5; return 5; } factors->f = 7; } else if (factors->f == 7) { if (factors->n%7 == 0) { factors->n /= 7; return 7; } factors->f = 11; } else { if (factors->n%factors->f == 0) { factors->n /= factors->f; return factors->f; } factors->f++; } } if (factors->n != 1) { unsigned tmp = factors->n; factors->n = 1; return tmp; } return 1; } #define TCI_USE_EXPENSIVE_PARTITION 0 #if TCI_USE_EXPENSIVE_PARTITION /* * Assumes base > 0 and power >= 0. */ static int ipow(int base, int power) { int p = 1; for (int mask = 0x1;mask <= power;mask <<= 1) { if (power&mask) p *= base; base *= base; } return p; } #endif void tci_partition_2x2(unsigned nthread, uint64_t work1, unsigned max1, uint64_t work2, unsigned max2, unsigned* nt1, unsigned* nt2) { max1 = TCI_MIN(TCI_MAX(max1, 1), nthread); max2 = TCI_MIN(TCI_MAX(max2, 1), nthread); if (nthread < 4) { if (max2 < max1 || (max1 == max2 && work1 >= work2)) { *nt1 = nthread; *nt2 = 1; } else { *nt1 = 1; *nt2 = nthread; } return; } tci_prime_factors factors; tci_prime_factorization(nthread, &factors); #if !TCI_USE_EXPENSIVE_PARTITION unsigned num1 = 1; unsigned num2 = 1; unsigned f; while ((f = tci_next_prime_factor(&factors)) > 1) { if ((work2 >= work1 || num1*f > max1) && num2*f <= max2) { work2 /= f; num2 *= f; } else { work1 /= f; num1 *= f; } } *nt1 = num1; *nt2 = num2; #else /* * Eight distinct prime factors handles all numbers up to 223092870 */ int fact[8]; int mult[8]; int nfact = 1; fact[0] = tci_next_prime_factor(&factors); mult[0] = 1; int f; while ((f = tci_next_prime_factor(&factors)) > 1) { if (f == fact[nfact-1]) { mult[nfact-1]++; } else { nfact++; fact[nfact-1] = f; mult[nfact-1] = 1; } } int ntake[8] = {0}; int64_t min_diff = INT64_MAX; bool done = false; while (!done) { int x = 1; int y = 1; for (int i = 0;i < nfact;i++) { x *= ipow(fact[i], ntake[i]); y *= ipow(fact[i], mult[i]-ntake[i]); } int64_t diff = llabs(x*work2 - y*work1); if (diff < min_diff) { min_diff = diff; *nt1 = x; *nt2 = y; } for (int i = 0;i < nfact;i++) { if (++ntake[i] > mult[i]) { ntake[i] = 0; if (i == nfact-1) done = true; else continue; } break; } } #endif assert((*nt1)*(*nt2) == nthread); }
cg.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 3.0 structured OpenMP C versions - CG This benchmark is an OpenMP C version of the NPB CG code. The OpenMP C 2.3 versions are derived by RWCP from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. 3.0 translation is performed by the UVSQ. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Authors: M. Yarrow C. Kuszmaul OpenMP C version: S. Satoh 3.0 structure translation: F. Conti --------------------------------------------------------------------*/ /* c--------------------------------------------------------------------- c Note: please observe that in the routine conj_grad three c implementations of the sparse matrix-vector multiply have c been supplied. The default matrix-vector multiply is not c loop unrolled. The alternate implementations are unrolled c to a depth of 2 and unrolled to a depth of 8. Please c experiment with these to find the fastest for your particular c architecture. If reporting timing results, any of these three may c be used without penalty. c--------------------------------------------------------------------- */ #include "../common/npb-C.h" #include "npbparams.h" #define NZ NA*(NONZER+1)*(NONZER+1)+NA*(NONZER+2) /* global variables */ /* common /partit_size/ */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /main_int_mem/ */ static int colidx[NZ+1]; /* colidx[1:NZ] */ static int rowstr[NA+1+1]; /* rowstr[1:NA+1] */ static int iv[2*NA+1+1]; /* iv[1:2*NA+1] */ static int arow[NZ+1]; /* arow[1:NZ] */ static int acol[NZ+1]; /* acol[1:NZ] */ /* common /main_flt_mem/ */ static double v[NA+1+1]; /* v[1:NA+1] */ static double aelt[NZ+1]; /* aelt[1:NZ] */ static double a[NZ+1]; /* a[1:NZ] */ static double x[NA+2+1]; /* x[1:NA+2] */ static double z[NA+2+1]; /* z[1:NA+2] */ static double p[NA+2+1]; /* p[1:NA+2] */ static double q[NA+2+1]; /* q[1:NA+2] */ static double r[NA+2+1]; /* r[1:NA+2] */ //static double w[NA+2+1]; /* w[1:NA+2] */ /* common /urando/ */ static double amult; static double tran; /* function declarations */ static void conj_grad (int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], //double w[], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int nonzer, int firstrow, int lastrow, int firstcol, int lastcol, double rcond, int arow[], int acol[], double aelt[], double v[], int iv[], double shift ); static void sparse(double a[], int colidx[], int rowstr[], int n, int arow[], int acol[], double aelt[], int firstrow, int lastrow, double x[], boolean mark[], int nzloc[], int nnza); static void sprnvc(int n, int nz, double v[], int iv[], int nzloc[], int mark[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); /*-------------------------------------------------------------------- program cg --------------------------------------------------------------------*/ int main(int argc, char **argv) { int i, j, k, it; int nthreads = 1; double zeta; double rnorm; double norm_temp11; double norm_temp12; double t, mflops; char class; boolean verified; double zeta_verify_value, epsilon; firstrow = 1; lastrow = NA; firstcol = 1; lastcol = NA; if (NA == 1400 && NONZER == 7 && NITER == 15 && SHIFT == 10.0) { class = 'S'; zeta_verify_value = 8.5971775078648; } else if (NA == 7000 && NONZER == 8 && NITER == 15 && SHIFT == 12.0) { class = 'W'; zeta_verify_value = 10.362595087124; } else if (NA == 14000 && NONZER == 11 && NITER == 15 && SHIFT == 20.0) { class = 'A'; zeta_verify_value = 17.130235054029; } else if (NA == 75000 && NONZER == 13 && NITER == 75 && SHIFT == 60.0) { class = 'B'; zeta_verify_value = 22.712745482631; } else if (NA == 150000 && NONZER == 15 && NITER == 75 && SHIFT == 110.0) { class = 'C'; zeta_verify_value = 28.973605592845; } else { class = 'U'; } printf("\n\n NAS Parallel Benchmarks 3.0 structured OpenMP C version" " - CG Benchmark\n"); printf(" Size: %10d\n", NA); printf(" Iterations: %5d\n", NITER); naa = NA; nzz = NZ; /*-------------------------------------------------------------------- c Initialize random number generator c-------------------------------------------------------------------*/ tran = 314159265.0; amult = 1220703125.0; zeta = randlc( &tran, amult ); /*-------------------------------------------------------------------- c c-------------------------------------------------------------------*/ makea(naa, nzz, a, colidx, rowstr, NONZER, firstrow, lastrow, firstcol, lastcol, RCOND, arow, acol, aelt, v, iv, SHIFT); /*--------------------------------------------------------------------- c Note: as a result of the above call to makea: c values of j used in indexing rowstr go from 1 --> lastrow-firstrow+1 c values of colidx which are col indexes go from firstcol --> lastcol c So: c Shift the col index vals from actual (firstcol --> lastcol ) c to local, i.e., (1 --> lastcol-firstcol+1) c---------------------------------------------------------------------*/ { #pragma omp parallel for for (j = 1; j <= lastrow - firstrow + 1; j++) { #pragma omp parallel for for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol + 1; } } /*-------------------------------------------------------------------- c set starting vector to (1, 1, .... 1) c-------------------------------------------------------------------*/ #pragma omp parallel for for (i = 1; i <= NA+1; i++) { x[i] = 1.0; } #pragma omp parallel for for (j = 1; j <= lastcol-firstcol+1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = 0.0; p[j] = 0.0; } }// end omp parallel zeta = 0.0; /*------------------------------------------------------------------- c----> c Do one iteration untimed to init all code and data page tables c----> (then reinit, start timing, to niter its) c-------------------------------------------------------------------*/ #pragma omp parallel for for (it = 1; it <= 1; it++) { /*-------------------------------------------------------------------- c The call to the conjugate gradient routine: c-------------------------------------------------------------------*/ conj_grad (colidx, rowstr, x, z, a, p, q, r,/* w,*/ &rnorm); /*-------------------------------------------------------------------- c zeta = shift + 1/(x.z) c So, first: (x.z) c Also, find norm of z c So, first: (z.z) c-------------------------------------------------------------------*/ norm_temp11 = 0.0; norm_temp12 = 0.0; for (j = 1; j <= lastcol-firstcol+1; j++) { norm_temp11 = norm_temp11 + x[j]*z[j]; norm_temp12 = norm_temp12 + z[j]*z[j]; } norm_temp12 = 1.0 / sqrt( norm_temp12 ); /*-------------------------------------------------------------------- c Normalize z to obtain x c-------------------------------------------------------------------*/ for (j = 1; j <= lastcol-firstcol+1; j++) { x[j] = norm_temp12*z[j]; } } /* end of do one iteration untimed */ /*-------------------------------------------------------------------- c set starting vector to (1, 1, .... 1) c-------------------------------------------------------------------*/ for (i = 1; i <= NA+1; i++) { x[i] = 1.0; } zeta = 0.0; timer_clear( 1 ); timer_start( 1 ); /*-------------------------------------------------------------------- c----> c Main Iteration for inverse power method c----> c-------------------------------------------------------------------*/ for (it = 1; it <= NITER; it++) { /*-------------------------------------------------------------------- c The call to the conjugate gradient routine: c-------------------------------------------------------------------*/ conj_grad(colidx, rowstr, x, z, a, p, q, r/*, w*/, &rnorm); /*-------------------------------------------------------------------- c zeta = shift + 1/(x.z) c So, first: (x.z) c Also, find norm of z c So, first: (z.z) c-------------------------------------------------------------------*/ norm_temp11 = 0.0; norm_temp12 = 0.0; for (j = 1; j <= lastcol-firstcol+1; j++) { norm_temp11 = norm_temp11 + x[j]*z[j]; norm_temp12 = norm_temp12 + z[j]*z[j]; } norm_temp12 = 1.0 / sqrt( norm_temp12 ); zeta = SHIFT + 1.0 / norm_temp11; if( it == 1 ) { printf(" iteration ||r|| zeta\n"); } printf(" %5d %20.14e%20.13e\n", it, rnorm, zeta); /*-------------------------------------------------------------------- c Normalize z to obtain x c-------------------------------------------------------------------*/ for (j = 1; j <= lastcol-firstcol+1; j++) { x[j] = norm_temp12*z[j]; } } /* end of main iter inv pow meth */ { #if defined(_OPENMP) nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop( 1 ); /*-------------------------------------------------------------------- c End of timed section c-------------------------------------------------------------------*/ t = timer_read( 1 ); printf(" Benchmark completed\n"); epsilon = 1.0e-10; if (class != 'U') { if (fabs(zeta - zeta_verify_value) <= epsilon) { verified = TRUE; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.12e\n", zeta); printf(" Error is %20.12e\n", zeta - zeta_verify_value); } else { verified = FALSE; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.12e\n", zeta); printf(" The correct zeta is %20.12e\n", zeta_verify_value); } } else { verified = FALSE; printf(" Problem size unknown\n"); printf(" NO VERIFICATION PERFORMED\n"); } if ( t != 0.0 ) { mflops = (2.0*NITER*NA) * (3.0+(NONZER*(NONZER+1)) + 25.0*(5.0+(NONZER*(NONZER+1))) + 3.0 ) / t / 1000000.0; } else { mflops = 0.0; } c_print_results("CG", class, NA, 0, 0, NITER, nthreads, t, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void conj_grad ( int colidx[], /* colidx[1:nzz] */ int rowstr[], /* rowstr[1:naa+1] */ double x[], /* x[*] */ double z[], /* z[*] */ double a[], /* a[1:nzz] */ double p[], /* p[*] */ double q[], /* q[*] */ double r[], /* r[*] */ //double w[], /* w[*] */ double *rnorm ) /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*--------------------------------------------------------------------- c Floaging point arrays here are named as in NPB1 spec discussion of c CG algorithm c---------------------------------------------------------------------*/ { static int callcount = 0; double d, sum, rho, rho0, alpha, beta; int i, j, k; int cgit, cgitmax = 25; rho = 0.0; /*-------------------------------------------------------------------- c Initialize the CG algorithm: c-------------------------------------------------------------------*/ { #pragma omp parallel for for (j = 1; j <= naa+1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = x[j]; p[j] = r[j]; //w[j] = 0.0; } /*-------------------------------------------------------------------- c rho = r.r c Now, obtain the norm of r: First, sum squares of r elements locally... c-------------------------------------------------------------------*/ #pragma omp parallel for reduction(+:rho) for (j = 1; j <= lastcol-firstcol+1; j++) { rho = rho + r[j]*r[j]; } }/* end omp parallel */ /*-------------------------------------------------------------------- c----> c The conj grad iteration loop c----> c-------------------------------------------------------------------*/ for (cgit = 1; cgit <= cgitmax; cgit++) { rho0 = rho; d = 0.0; rho = 0.0; { /*-------------------------------------------------------------------- c q = A.p c The partition submatrix-vector multiply: use workspace w c--------------------------------------------------------------------- C C NOTE: this version of the multiply is actually (slightly: maybe %5) C faster on the sp2 on 16 nodes than is the unrolled-by-2 version C below. On the Cray t3d, the reverse is true, i.e., the C unrolled-by-two version is some 10% faster. C The unrolled-by-8 version below is significantly faster C on the Cray t3d - overall speed of code is 1.5 times faster. */ /* rolled version */ #pragma omp parallel for private(sum) for (j = 1; j <= lastrow-firstrow+1; j++) { sum = 0.0; #pragma omp parallel for reduction(+:sum) for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k]*p[colidx[k]]; } //w[j] = sum; q[j] = sum; } /* unrolled-by-two version for (j = 1; j <= lastrow-firstrow+1; j++) { int iresidue; double sum1, sum2; i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 2; sum1 = 0.0; sum2 = 0.0; if (iresidue == 1) sum1 = sum1 + a[i]*p[colidx[i]]; for (k = i+iresidue; k <= rowstr[j+1]-2; k += 2) { sum1 = sum1 + a[k] * p[colidx[k]]; sum2 = sum2 + a[k+1] * p[colidx[k+1]]; } w[j] = sum1 + sum2; } */ /* unrolled-by-8 version for (j = 1; j <= lastrow-firstrow+1; j++) { int iresidue; i = rowstr[j]; iresidue = (rowstr[j+1]-i) % 8; sum = 0.0; for (k = i; k <= i+iresidue-1; k++) { sum = sum + a[k] * p[colidx[k]]; } for (k = i+iresidue; k <= rowstr[j+1]-8; k += 8) { sum = sum + a[k ] * p[colidx[k ]] + a[k+1] * p[colidx[k+1]] + a[k+2] * p[colidx[k+2]] + a[k+3] * p[colidx[k+3]] + a[k+4] * p[colidx[k+4]] + a[k+5] * p[colidx[k+5]] + a[k+6] * p[colidx[k+6]] + a[k+7] * p[colidx[k+7]]; } w[j] = sum; } */ /* for (j = 1; j <= lastcol-firstcol+1; j++) { q[j] = w[j]; } */ /*-------------------------------------------------------------------- c Clear w for reuse... c-------------------------------------------------------------------*/ /* for (j = 1; j <= lastcol-firstcol+1; j++) { w[j] = 0.0; } */ /*-------------------------------------------------------------------- c Obtain p.q c-------------------------------------------------------------------*/ #pragma omp parallel for reduction(+:d) for (j = 1; j <= lastcol-firstcol+1; j++) { d = d + p[j]*q[j]; } /*-------------------------------------------------------------------- c Obtain alpha = rho / (p.q) c-------------------------------------------------------------------*/ //#pragma omp single alpha = rho0 / d; /*-------------------------------------------------------------------- c Save a temporary of rho c-------------------------------------------------------------------*/ /* rho0 = rho;*/ /*--------------------------------------------------------------------- c Obtain z = z + alpha*p c and r = r - alpha*q c---------------------------------------------------------------------*/ #pragma omp parallel for for (j = 1; j <= lastcol-firstcol+1; j++) { z[j] = z[j] + alpha*p[j]; r[j] = r[j] - alpha*q[j]; // } /*--------------------------------------------------------------------- c rho = r.r c Now, obtain the norm of r: First, sum squares of r elements locally... c---------------------------------------------------------------------*/ /* for (j = 1; j <= lastcol-firstcol+1; j++) {*/ rho = rho + r[j]*r[j]; } //#pragma omp barrier /*-------------------------------------------------------------------- c Obtain beta: c-------------------------------------------------------------------*/ //#pragma omp single beta = rho / rho0; /*-------------------------------------------------------------------- c p = r + beta*p c-------------------------------------------------------------------*/ #pragma omp parallel for for (j = 1; j <= lastcol-firstcol+1; j++) { p[j] = r[j] + beta*p[j]; } callcount++; } /* end omp parallel */ } /* end of do cgit=1,cgitmax */ /*--------------------------------------------------------------------- c Compute residual norm explicitly: ||r|| = ||x - A.z|| c First, form A.z c The partition submatrix-vector multiply c---------------------------------------------------------------------*/ sum = 0.0; { #pragma omp parallel for private(d) for (j = 1; j <= lastrow-firstrow+1; j++) { d = 0.0; #pragma omp parallel for reduction(+:d) for (k = rowstr[j]; k <= rowstr[j+1]-1; k++) { d = d + a[k]*z[colidx[k]]; } r[j] = d; } /*-------------------------------------------------------------------- c At this point, r contains A.z c-------------------------------------------------------------------*/ #pragma omp parallel for private(d ) reduction(+:sum) for (j = 1; j <= lastcol-firstcol+1; j++) { d = x[j] - r[j]; sum = sum + d*d; } } //end omp parallel (*rnorm) = sqrt(sum); } /*--------------------------------------------------------------------- c generate the test problem for benchmark 6 c makea generates a sparse matrix with a c prescribed sparsity distribution c c parameter type usage c c input c c n i number of cols/rows of matrix c nz i nonzeros as declared array size c rcond r*8 condition number c shift r*8 main diagonal shift c c output c c a r*8 array for nonzeros c colidx i col indices c rowstr i row pointers c c workspace c c iv, arow, acol i c v, aelt r*8 c---------------------------------------------------------------------*/ static void makea( int n, int nz, double a[], /* a[1:nz] */ int colidx[], /* colidx[1:nz] */ int rowstr[], /* rowstr[1:n+1] */ int nonzer, int firstrow, int lastrow, int firstcol, int lastcol, double rcond, int arow[], /* arow[1:nz] */ int acol[], /* acol[1:nz] */ double aelt[], /* aelt[1:nz] */ double v[], /* v[1:n+1] */ int iv[], /* iv[1:2*n+1] */ double shift ) { int i, nnza, iouter, ivelt, ivelt1, irow, nzv; /*-------------------------------------------------------------------- c nonzer is approximately (int(sqrt(nnza /n))); c-------------------------------------------------------------------*/ double size, ratio, scale; int jcol; size = 1.0; ratio = pow(rcond, (1.0 / (double)n)); nnza = 0; /*--------------------------------------------------------------------- c Initialize colidx(n+1 .. 2n) to zero. c Used by sprnvc to mark nonzero positions c---------------------------------------------------------------------*/ #pragma omp parallel for for (i = 1; i <= n; i++) { colidx[n+i] = 0; } for (iouter = 1; iouter <= n; iouter++) { nzv = nonzer; sprnvc(n, nzv, v, iv, &(colidx[0]), &(colidx[n])); vecset(n, v, iv, &nzv, iouter, 0.5); for (ivelt = 1; ivelt <= nzv; ivelt++) { jcol = iv[ivelt]; if (jcol >= firstcol && jcol <= lastcol) { scale = size * v[ivelt]; for (ivelt1 = 1; ivelt1 <= nzv; ivelt1++) { irow = iv[ivelt1]; if (irow >= firstrow && irow <= lastrow) { nnza = nnza + 1; if (nnza > nz) { printf("Space for matrix elements exceeded in" " makea\n"); printf("nnza, nzmax = %d, %d\n", nnza, nz); printf("iouter = %d\n", iouter); exit(1); } acol[nnza] = jcol; arow[nnza] = irow; aelt[nnza] = v[ivelt1] * scale; } } } } size = size * ratio; } /*--------------------------------------------------------------------- c ... add the identity * rcond to the generated matrix to bound c the smallest eigenvalue from below by rcond c---------------------------------------------------------------------*/ for (i = firstrow; i <= lastrow; i++) { if (i >= firstcol && i <= lastcol) { iouter = n + i; nnza = nnza + 1; if (nnza > nz) { printf("Space for matrix elements exceeded in makea\n"); printf("nnza, nzmax = %d, %d\n", nnza, nz); printf("iouter = %d\n", iouter); exit(1); } acol[nnza] = i; arow[nnza] = i; aelt[nnza] = rcond - shift; } } /*--------------------------------------------------------------------- c ... make the sparse matrix from list of elements with duplicates c (v and iv are used as workspace) c---------------------------------------------------------------------*/ sparse(a, colidx, rowstr, n, arow, acol, aelt, firstrow, lastrow, v, &(iv[0]), &(iv[n]), nnza); } /*--------------------------------------------------- c generate a sparse matrix from a list of c [col, row, element] tri c---------------------------------------------------*/ static void sparse( double a[], /* a[1:*] */ int colidx[], /* colidx[1:*] */ int rowstr[], /* rowstr[1:*] */ int n, int arow[], /* arow[1:*] */ int acol[], /* acol[1:*] */ double aelt[], /* aelt[1:*] */ int firstrow, int lastrow, double x[], /* x[1:n] */ boolean mark[], /* mark[1:n] */ int nzloc[], /* nzloc[1:n] */ int nnza) /*--------------------------------------------------------------------- c rows range from firstrow to lastrow c the rowstr pointers are defined for nrows = lastrow-firstrow+1 values c---------------------------------------------------------------------*/ { int nrows; int i, j, jajp1, nza, k, nzrow; double xi; /*-------------------------------------------------------------------- c how many rows of result c-------------------------------------------------------------------*/ nrows = lastrow - firstrow + 1; /*-------------------------------------------------------------------- c ...count the number of triples in each row c-------------------------------------------------------------------*/ #pragma omp parallel for for (j = 1; j <= n; j++) { rowstr[j] = 0; mark[j] = FALSE; } rowstr[n+1] = 0; for (nza = 1; nza <= nnza; nza++) { j = (arow[nza] - firstrow + 1) + 1; rowstr[j] = rowstr[j] + 1; } rowstr[1] = 1; for (j = 2; j <= nrows+1; j++) { rowstr[j] = rowstr[j] + rowstr[j-1]; } /*--------------------------------------------------------------------- c ... rowstr(j) now is the location of the first nonzero c of row j of a c---------------------------------------------------------------------*/ /*--------------------------------------------------------------------- c ... preload data pages c---------------------------------------------------------------------*/ #pragma omp parallel for for(j = 0;j <= nrows-1;j++) { #pragma omp parallel for firstprivate(j) for(k = rowstr[j];k <= rowstr[j+1]-1;k++) a[k] = 0.0; } /*-------------------------------------------------------------------- c ... do a bucket sort of the triples on the row index c-------------------------------------------------------------------*/ for (nza = 1; nza <= nnza; nza++) { j = arow[nza] - firstrow + 1; k = rowstr[j]; a[k] = aelt[nza]; colidx[k] = acol[nza]; rowstr[j] = rowstr[j] + 1; } /*-------------------------------------------------------------------- c ... rowstr(j) now points to the first element of row j+1 c-------------------------------------------------------------------*/ for (j = nrows; j >= 1; j--) { rowstr[j+1] = rowstr[j]; } rowstr[1] = 1; /*-------------------------------------------------------------------- c ... generate the actual output rows by adding elements c-------------------------------------------------------------------*/ nza = 0; #pragma omp parallel for for (i = 1; i <= n; i++) { x[i] = 0.0; mark[i] = FALSE; } jajp1 = rowstr[1]; for (j = 1; j <= nrows; j++) { nzrow = 0; /*-------------------------------------------------------------------- c ...loop over the jth row of a c-------------------------------------------------------------------*/ for (k = jajp1; k < rowstr[j+1]; k++) { i = colidx[k]; x[i] = x[i] + a[k]; if ( mark[i] == FALSE && x[i] != 0.0) { mark[i] = TRUE; nzrow = nzrow + 1; nzloc[nzrow] = i; } } /*-------------------------------------------------------------------- c ... extract the nonzeros of this row c-------------------------------------------------------------------*/ for (k = 1; k <= nzrow; k++) { i = nzloc[k]; mark[i] = FALSE; xi = x[i]; x[i] = 0.0; if (xi != 0.0) { nza = nza + 1; a[nza] = xi; colidx[nza] = i; } } jajp1 = rowstr[j+1]; rowstr[j+1] = nza + rowstr[1]; } } /*--------------------------------------------------------------------- c generate a sparse n-vector (v, iv) c having nzv nonzeros c c mark(i) is set to 1 if position i is nonzero. c mark is all zero on entry and is reset to all zero before exit c this corrects a performance bug found by John G. Lewis, caused by c reinitialization of mark on every one of the n calls to sprnvc ---------------------------------------------------------------------*/ static void sprnvc( int n, int nz, double v[], /* v[1:*] */ int iv[], /* iv[1:*] */ int nzloc[], /* nzloc[1:n] */ int mark[] ) /* mark[1:n] */ { int nn1; int nzrow, nzv, ii, i; double vecelt, vecloc; nzv = 0; nzrow = 0; nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); /*-------------------------------------------------------------------- c nn1 is the smallest power of two not less than n c-------------------------------------------------------------------*/ while (nzv < nz) { vecelt = randlc(&tran, amult); /*-------------------------------------------------------------------- c generate an integer between 1 and n in a portable manner c-------------------------------------------------------------------*/ vecloc = randlc(&tran, amult); i = icnvrt(vecloc, nn1) + 1; if (i > n) continue; /*-------------------------------------------------------------------- c was this integer generated already? c-------------------------------------------------------------------*/ if (mark[i] == 0) { mark[i] = 1; nzrow = nzrow + 1; nzloc[nzrow] = i; nzv = nzv + 1; v[nzv] = vecelt; iv[nzv] = i; } } for (ii = 1; ii <= nzrow; ii++) { i = nzloc[ii]; mark[i] = 0; } } /*--------------------------------------------------------------------- * scale a double precision number x in (0,1) by a power of 2 and chop it *---------------------------------------------------------------------*/ static int icnvrt(double x, int ipwr2) { return ((int)(ipwr2 * x)); } /*-------------------------------------------------------------------- c set ith element of sparse vector (v, iv) with c nzv nonzeros to val c-------------------------------------------------------------------*/ static void vecset( int n, double v[], /* v[1:*] */ int iv[], /* iv[1:*] */ int *nzv, int i, double val) { int k; boolean set; set = FALSE; for (k = 1; k <= *nzv; k++) { if (iv[k] == i) { v[k] = val; set = TRUE; } } if (set == FALSE) { *nzv = *nzv + 1; v[*nzv] = val; iv[*nzv] = i; } }
pr63249.c
/* PR c++/63249 */ /* { dg-do compile } */ /* { dg-options "-Wall -W -fopenmp" } */ int foo (int *v, int A, int B) /* { dg-bogus "set but not used" } */ { int r = 0; int a = 2; /* { dg-bogus "set but not used" } */ int b = 4; /* { dg-bogus "set but not used" } */ #pragma omp target map(to: v[a:b]) r |= v[3]; #pragma omp target map(to: v[A:B]) r |= v[3]; return r; }
dahua_fmt_plug.c
/* * Format for cracking Dahua hashes. * * http://www.securityfocus.com/archive/1/529799 * https://github.com/depthsecurity/dahua_dvr_auth_bypass * * This software is Copyright (c) 2014 Dhiru Kholia <dhiru at openwall.com>, * and it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without# * modification, are permitted. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_dahua; #elif FMT_REGISTERS_H john_register_one(&fmt_dahua); #else #include <string.h> #if !FAST_FORMATS_OMP #undef _OPENMP #endif #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #ifdef __MIC__ #define OMP_SCALE 512 #else #define OMP_SCALE 32768 // tuned K8-dual HT #endif // __MIC__ #endif // OMP_SCALE #endif // _OPENMP #include "arch.h" #include "md5.h" #include "misc.h" #include "common.h" #include "formats.h" #include "johnswap.h" #include "params.h" #include "options.h" #include "memdbg.h" #include <ctype.h> #define FORMAT_LABEL "dahua" #define FORMAT_NAME "\"MD5 based authentication\" Dahua" #define FORMAT_TAG "$dahua$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define ALGORITHM_NAME "MD5 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 8 #define BINARY_ALIGN sizeof(uint32_t) #define SALT_SIZE 0 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests tests[] = { {"$dahua$4WzwxXxM", "888888"}, // from hashcat.net {"$dahua$HRG6OLE6", "Do You Even Lift?"}, {"$dahua$sh15yfFM", "666666"}, {"$dahua$6QNMIQGe", "admin"}, {"$dahua$g2UpKxOg", "passWOrd"}, {"$dahua$tlJwpbo6", ""}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *saved_len; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; 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_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_len); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p = ciphertext; int i; if (strncmp(p, FORMAT_TAG, TAG_LENGTH) != 0) return 0; p = p + TAG_LENGTH; if (!p) return 0; if (strlen(p) != BINARY_SIZE) return 0; for (i = 0; i < BINARY_SIZE; i++) if (!isalnum((int)(unsigned char)p[i])) return 0; return 1; } static void *get_binary(char *ciphertext) { static union { char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; char *p; char *out = buf.c; p = strrchr(ciphertext, '$') + 1; strncpy(out, p, BINARY_SIZE); return out; } #define COMMON_GET_HASH_VAR crypt_out #include "common-get-hash.h" // from hashcat.net (alxchk) static void compressor(unsigned char *in, unsigned char *out) { int i, j; for (i = 0, j = 0; i < 16; i += 2, j++) { out[j] = (in[i] + in[i+1]) % 62; if (out[j] < 10) { out[j] += 48; } else if (out[j] < 36) { out[j] += 55; } else { out[j] += 61; } } } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { // hash is compressor(md5(password)) MD5_CTX ctx; unsigned char *out = (unsigned char*)crypt_out[index]; unsigned char hash[16]; MD5_Init(&ctx); MD5_Update(&ctx, saved_key[index], saved_len[index]); MD5_Final(hash, &ctx); compressor(hash, out); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void dahua_set_key(char *key, int index) { saved_len[index] = strnzcpyn(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_dahua = { { 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, #ifdef _OPENMP FMT_OMP | FMT_OMP_BAD | #endif FMT_CASE | FMT_8_BIT, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, dahua_set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif
shear.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS H H EEEEE AAA RRRR % % SS H H E A A R R % % SSS HHHHH EEE AAAAA RRRR % % SS H H E A A R R % % SSSSS H H EEEEE A A R R % % % % % % MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The XShearImage() and YShearImage() methods are based on the paper "A Fast % Algorithm for General Raster Rotation" by Alan W. Paeth, Graphics % Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar % method based on the Paeth paper written by Michael Halle of the Spatial % Imaging Group, MIT Media Lab. % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob-private.h" #include "magick/cache-private.h" #include "magick/channel.h" #include "magick/color-private.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/decorate.h" #include "magick/distort.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/memory_.h" #include "magick/list.h" #include "magick/matrix.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/pixel-private.h" #include "magick/quantum.h" #include "magick/resource_.h" #include "magick/shear.h" #include "magick/statistic.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/token.h" #include "magick/transform.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C r o p T o F i t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropToFitImage() crops the sheared image as determined by the bounding box % as defined by width and height and shearing angles. % % The format of the CropToFitImage method is: % % MagickBooleanType CropToFitImage(Image **image, % const MagickRealType x_shear,const MagickRealType x_shear, % const MagickRealType width,const MagickRealType height, % const MagickBooleanType rotate,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear, width, height: Defines a region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CropToFitImage(Image **image, const MagickRealType x_shear,const MagickRealType y_shear, const MagickRealType width,const MagickRealType height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; register ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } geometry.x=(ssize_t) ceil(min.x-0.5); geometry.y=(ssize_t) ceil(min.y-0.5); geometry.width=(size_t) floor(max.x-min.x+0.5); geometry.height=(size_t) floor(max.y-min.y+0.5); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The amount of rotation calculated to deskew the image is saved in the % artifact "deskew:angle". % % If the artifact "deskew:auto-crop" is given the image will be automatically % cropped of the excess background. % % The format of the DeskewImage method is: % % Image *DeskewImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: separate background from foreground. % % o exception: return any errors or warnings in this structure. % */ static void RadonProjection(const Image *image,MatrixInfo *source_matrix, MatrixInfo *destination_matrix,const ssize_t sign,size_t *projection) { MatrixInfo *swap; register MatrixInfo *p, *q; register ssize_t x; size_t step; p=source_matrix; q=destination_matrix; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { register ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_number_threads(image,image,GetMatrixColumns(p),1) #endif for (x=0; x < (ssize_t) GetMatrixColumns(p); x++) { register ssize_t y; size_t sum; sum=0; for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++) { ssize_t delta; unsigned short element, neighbor; if (GetMatrixElement(p,x,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse) continue; delta=(ssize_t) element-(ssize_t) neighbor; sum+=delta*delta; } projection[GetMatrixColumns(p)+sign*x-1]=sum; } } static MagickBooleanType RadonTransform(const Image *image, const double threshold,size_t *projection,ExceptionInfo *exception) { CacheView *image_view; MatrixInfo *destination_matrix, *source_matrix; MagickBooleanType status; register ssize_t i; size_t count, width; ssize_t y; unsigned char byte; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrix=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrix=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); if ((source_matrix == (MatrixInfo *) NULL) || (destination_matrix == (MatrixInfo *) NULL)) { if (destination_matrix != (MatrixInfo *) NULL) destination_matrix=DestroyMatrixInfo(destination_matrix); if (source_matrix != (MatrixInfo *) NULL) source_matrix=DestroyMatrixInfo(source_matrix); return(MagickFalse); } if (NullMatrix(source_matrix) == MagickFalse) { destination_matrix=DestroyMatrixInfo(destination_matrix); source_matrix=DestroyMatrixInfo(source_matrix); return(MagickFalse); } for (i=0; i < 256; i++) { byte=(unsigned char) i; for (count=0; byte != 0; byte>>=1) count+=byte & 0x01; bits[i]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=(ssize_t) (image->columns+7)/8; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(p) < threshold) || ((MagickRealType) GetPixelGreen(p) < threshold) || ((MagickRealType) GetPixelBlue(p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrix,--i,y,&value); bit=0; byte=0; } p++; } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrix,--i,y,&value); } } RadonProjection(image,source_matrix,destination_matrix,-1,projection); (void) NullMatrix(source_matrix); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(p) < threshold) || ((MagickRealType) GetPixelGreen(p) < threshold) || ((MagickRealType) GetPixelBlue(p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrix,i++,y,&value); bit=0; byte=0; } p++; } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrix,i++,y,&value); } } RadonProjection(image,source_matrix,destination_matrix,1,projection); image_view=DestroyCacheView(image_view); destination_matrix=DestroyMatrixInfo(destination_matrix); source_matrix=DestroyMatrixInfo(source_matrix); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; MagickPixelPacket background; MagickRealType count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetMagickPixelPacket(image,&background); count=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *magick_restrict p; register ssize_t x; if ((y >= offset) && (y < ((ssize_t) image->rows-offset))) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) continue; for (x=0; x < (ssize_t) image->columns; x++) { if ((x >= offset) && (x < ((ssize_t) image->columns-offset))) continue; background.red+=QuantumScale*GetPixelRed(p); background.green+=QuantumScale*GetPixelGreen(p); background.blue+=QuantumScale*GetPixelBlue(p); background.opacity+=QuantumScale*GetPixelOpacity(p); count++; p++; } } image_view=DestroyCacheView(image_view); image->background_color.red=ClampToQuantum((MagickRealType) QuantumRange* background.red/count); image->background_color.green=ClampToQuantum((MagickRealType) QuantumRange* background.green/count); image->background_color.blue=ClampToQuantum((MagickRealType) QuantumRange* background.blue/count); image->background_color.opacity=ClampToQuantum((MagickRealType) QuantumRange* background.opacity/count); } MagickExport Image *DeskewImage(const Image *image,const double threshold, ExceptionInfo *exception) { AffineMatrix affine_matrix; const char *artifact; double degrees; Image *clone_image, *crop_image, *deskew_image, *median_image; MagickBooleanType status; RectangleInfo geometry; register ssize_t i; size_t max_projection, *projection, width; ssize_t skew; /* Compute deskew angle. */ for (width=1; width < ((image->columns+7)/8); width<<=1) ; projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1), sizeof(*projection)); if (projection == (size_t *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); status=RadonTransform(image,threshold,projection,exception); if (status == MagickFalse) { projection=(size_t *) RelinquishMagickMemory(projection); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } max_projection=0; skew=0; for (i=0; i < (ssize_t) (2*width-1); i++) { if (projection[i] > max_projection) { skew=i-(ssize_t) width+1; max_projection=projection[i]; } } projection=(size_t *) RelinquishMagickMemory(projection); degrees=RadiansToDegrees(-atan((double) skew/width/8)); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Deskew angle: %g",degrees); /* Deskew image. */ clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); { char angle[MaxTextExtent]; (void) FormatLocaleString(angle,MaxTextExtent,"%g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod); affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0)))); affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.tx=0.0; affine_matrix.ty=0.0; artifact=GetImageArtifact(image,"deskew:auto-crop"); if (IsMagickTrue(artifact) == MagickFalse) { deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); return(deskew_image); } /* Auto-crop image. */ GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact), exception); deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); if (deskew_image == (Image *) NULL) return((Image *) NULL); median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception); if (median_image == (Image *) NULL) { deskew_image=DestroyImage(deskew_image); return((Image *) NULL); } geometry=GetImageBoundingBox(median_image,exception); median_image=DestroyImage(median_image); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: " "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); crop_image=CropImage(deskew_image,&geometry,exception); deskew_image=DestroyImage(deskew_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e g r a l R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IntegralRotateImage() rotates the image an integral of 90 degrees. It % allocates the memory necessary for the new Image structure and returns a % pointer to the rotated image. % % The format of the IntegralRotateImage method is: % % Image *IntegralRotateImage(const Image *image,size_t rotations, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o rotations: Specifies the number of 90 degree rotations. % */ MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations, ExceptionInfo *exception) { #define RotateImageTag "Rotate/Image" CacheView *image_view, *rotate_view; Image *rotate_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; if (rotations == 0) return(CloneImage(image,0,0,MagickTrue,exception)); if ((rotations == 1) || (rotations == 3)) rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); else rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (rotate_image == (Image *) NULL) return((Image *) NULL); /* Integral rotate the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; for (tile_x=0; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict rotate_indexes; register PixelPacket *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (y=0; y < (ssize_t) width; y++) { register const PixelPacket *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t) (rotate_image->columns-(tile_y+height)),y+tile_x,height,1, exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } tile_pixels=p+(height-1)*width+y; for (x=0; x < (ssize_t) height; x++) { *q++=(*tile_pixels); tile_pixels-=width; } rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view); if ((indexes != (IndexPacket *) NULL) && (rotate_indexes != (IndexPacket *) NULL)) { register const IndexPacket *magick_restrict tile_indexes; tile_indexes=indexes+(height-1)*width+y; for (x=0; x < (ssize_t) height; x++) { *rotate_indexes++=(*tile_indexes); tile_indexes-=width; } } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict rotate_indexes; register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); q=QueueCacheViewAuthenticPixels(rotate_view,0,(ssize_t) (image->rows-y- 1),image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view); q+=image->columns; for (x=0; x < (ssize_t) image->columns; x++) *--q=(*p++); if ((indexes != (IndexPacket *) NULL) && (rotate_indexes != (IndexPacket *) NULL)) for (x=0; x < (ssize_t) image->columns; x++) SetPixelIndex(rotate_indexes+image->columns-x-1, GetPixelIndex(indexes+x)); sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,image,image->rows/tile_height,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; for (tile_x=0; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict rotate_indexes; register PixelPacket *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; break; } indexes=GetCacheViewVirtualIndexQueue(image_view); for (y=0; y < (ssize_t) width; y++) { register const PixelPacket *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+ rotate_image->rows-(tile_x+width)),height,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } tile_pixels=p+(width-1)-y; for (x=0; x < (ssize_t) height; x++) { *q++=(*tile_pixels); tile_pixels+=width; } rotate_indexes=GetCacheViewAuthenticIndexQueue(rotate_view); if ((indexes != (IndexPacket *) NULL) && (rotate_indexes != (IndexPacket *) NULL)) { register const IndexPacket *magick_restrict tile_indexes; tile_indexes=indexes+(width-1)-y; for (x=0; x < (ssize_t) height; x++) { *rotate_indexes++=(*tile_indexes); tile_indexes+=width; } } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.height != 0) page.y=(ssize_t) (page.height-rotate_image->rows-page.y); break; } default: break; } rotate_view=DestroyCacheView(rotate_view); image_view=DestroyCacheView(image_view); rotate_image->type=image->type; rotate_image->page=page; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + X S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % XShearImage() shears the image in the X direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a vertical % Y-axis. X shears will widen an image creating 'empty' triangles on the left % and right sides of the source image. % % The format of the XShearImage method is: % % MagickBooleanType XShearImage(Image *image,const MagickRealType degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A MagickRealType representing the shearing angle along the X % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType XShearImage(Image *image,const MagickRealType degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define XShearImageTag "XShear/Image" typedef enum { LEFT, RIGHT } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket background; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetMagickPixelPacket(image,&background); SetMagickPixelPacket(image,&image->background_color,(IndexPacket *) NULL, &background); if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&background); /* X shear image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { MagickPixelPacket pixel, source, destination; MagickRealType area, displacement; register IndexPacket *magick_restrict indexes, *magick_restrict shear_indexes; register PixelPacket *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1, exception); if (p == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); p+=x_offset; indexes+=x_offset; displacement=degrees*(MagickRealType) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=(ssize_t) floor((double) displacement); area=(MagickRealType) (displacement-step); step++; pixel=background; GetMagickPixelPacket(image,&source); GetMagickPixelPacket(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step; shear_indexes=indexes-step; for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { SetMagickPixelPacket(image,++p,++indexes,&pixel); q++; shear_indexes++; continue; } SetMagickPixelPacket(image,p,indexes,&source); MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &source,(MagickRealType) GetPixelOpacity(p),area,&destination); SetPixelPacket(image,&destination,q++,shear_indexes++); SetMagickPixelPacket(image,p++,indexes++,&pixel); } MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &background,(MagickRealType) background.opacity,area,&destination); SetPixelPacket(image,&destination,q++,shear_indexes++); for (i=0; i < (step-1); i++) SetPixelPacket(image,&background,q++,shear_indexes++); break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width; indexes+=width; q=p+step; shear_indexes=indexes+step; for (i=0; i < (ssize_t) width; i++) { p--; indexes--; q--; shear_indexes--; if ((size_t) (x_offset+width+step-i) > image->columns) continue; SetMagickPixelPacket(image,p,indexes,&source); MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &source,(MagickRealType) GetPixelOpacity(p),area,&destination); SetPixelPacket(image,&destination,q,shear_indexes); SetMagickPixelPacket(image,p,indexes,&pixel); } MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &background,(MagickRealType) background.opacity,area,&destination); SetPixelPacket(image,&destination,--q,--shear_indexes); for (i=0; i < (step-1); i++) SetPixelPacket(image,&background,--q,--shear_indexes); break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_XShearImage) #endif proceed=SetImageProgress(image,XShearImageTag,progress++,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const MagickRealType degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A MagickRealType representing the shearing angle along the Y % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType YShearImage(Image *image,const MagickRealType degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define YShearImageTag "YShear/Image" typedef enum { UP, DOWN } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket background; ssize_t x; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetMagickPixelPacket(image,&background); SetMagickPixelPacket(image,&image->background_color,(IndexPacket *) NULL, &background); if (image->colorspace == CMYKColorspace) ConvertRGBToCMYK(&background); /* Y Shear image. */ status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { ssize_t step; MagickPixelPacket pixel, source, destination; MagickRealType area, displacement; register IndexPacket *magick_restrict indexes, *magick_restrict shear_indexes; register ssize_t i; register PixelPacket *magick_restrict p, *magick_restrict q; ShearDirection direction; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); p+=y_offset; indexes+=y_offset; displacement=degrees*(MagickRealType) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=(ssize_t) floor((double) displacement); area=(MagickRealType) (displacement-step); step++; pixel=background; GetMagickPixelPacket(image,&source); GetMagickPixelPacket(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step; shear_indexes=indexes-step; for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { SetMagickPixelPacket(image,++p,++indexes,&pixel); q++; shear_indexes++; continue; } SetMagickPixelPacket(image,p,indexes,&source); MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &source,(MagickRealType) GetPixelOpacity(p),area,&destination); SetPixelPacket(image,&destination,q++,shear_indexes++); SetMagickPixelPacket(image,p++,indexes++,&pixel); } MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &background,(MagickRealType) background.opacity,area,&destination); SetPixelPacket(image,&destination,q++,shear_indexes++); for (i=0; i < (step-1); i++) SetPixelPacket(image,&background,q++,shear_indexes++); break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height; indexes+=height; q=p+step; shear_indexes=indexes+step; for (i=0; i < (ssize_t) height; i++) { p--; indexes--; q--; shear_indexes--; if ((size_t) (y_offset+height+step-i) > image->rows) continue; SetMagickPixelPacket(image,p,indexes,&source); MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &source,(MagickRealType) GetPixelOpacity(p),area,&destination); SetPixelPacket(image,&destination,q,shear_indexes); SetMagickPixelPacket(image,p,indexes,&pixel); } MagickPixelCompositeAreaBlend(&pixel,(MagickRealType) pixel.opacity, &background,(MagickRealType) background.opacity,area,&destination); SetPixelPacket(image,&destination,--q,--shear_indexes); for (i=0; i < (step-1); i++) SetPixelPacket(image,&background,--q,--shear_indexes); break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_YShearImage) #endif proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; 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 ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass) == MagickFalse) { InheritException(exception,&integral_image->exception); integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->matte == MagickFalse) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel); /* Compute image size. */ bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5); bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)- image->columns)/2.0-0.5); bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)- image->rows)/2.0-0.5); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->matte == MagickFalse) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel); status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x, (ssize_t) (shear_image->rows-image->rows)/2,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t) (shear_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,(MagickRealType) image->rows,MagickFalse,exception); shear_image->matte=image->matte; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ 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); angle=degrees-360.0*(ssize_t) (degrees/360.0); if (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; /* Calculate shear equations. */ integral_image=IntegralRotateImage(image,rotations,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass) == MagickFalse) { InheritException(exception,&integral_image->exception); integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->matte == MagickFalse) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5); bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,exception); integral_image=DestroyImage(integral_image); if (rotate_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Rotate the image. */ status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t) (rotate_image->rows-height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t) (rotate_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t) (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows- bounds.height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width, (MagickRealType) height,MagickTrue,exception); rotate_image->matte=image->matte; rotate_image->compose=image->compose; rotate_image->page.width=0; rotate_image->page.height=0; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); }
GB_kroner.c
//------------------------------------------------------------------------------ // GB_kroner: Kronecker product, C = kron (A,B) //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // C = kron(A,B) where op determines the binary multiplier to use. The type of // A and B are compatible with the x and y inputs of z=op(x,y), but can be // different. The type of C is the type of z. C is hypersparse if either A // or B are hypersparse. // FUTURE: this would be faster with built-in types and operators. // FUTURE: at most one thread is used for each vector of C=kron(A,B). The // matrix C is normally very large, but if both A and B are n-by-1, then C is // n^2-by-1 and only a single thread is used. A better method for this case // would construct vectors of C in parallel. // FUTURE: each vector C(:,k) takes O(nnz(C(:,k))) work, but this is not // accounted for in the parallel load-balancing. #include "GB_kron.h" #define GB_FREE_WORK \ { \ GB_phbix_free (A2) ; \ GB_phbix_free (B2) ; \ } #define GB_FREE_ALL \ { \ GB_FREE_WORK ; \ GB_phbix_free (C) ; \ } GrB_Info GB_kroner // C = kron (A,B) ( GrB_Matrix C, // output matrix (static header) const bool C_is_csc, // desired format of C const GrB_BinaryOp op, // multiply operator const GrB_Matrix A_in, // input matrix bool A_is_pattern, // true if values of A are not used const GrB_Matrix B_in, // input matrix bool B_is_pattern, // true if values of B are not used GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; ASSERT (C != NULL && C->static_header) ; struct GB_Matrix_opaque A2_header, B2_header ; GrB_Matrix A2 = GB_clear_static_header (&A2_header) ; GrB_Matrix B2 = GB_clear_static_header (&B2_header) ; ASSERT_MATRIX_OK (A_in, "A_in for kron (A,B)", GB0) ; ASSERT_MATRIX_OK (B_in, "B_in for kron (A,B)", GB0) ; ASSERT_BINARYOP_OK (op, "op for kron (A,B)", GB0) ; //-------------------------------------------------------------------------- // finish any pending work //-------------------------------------------------------------------------- GB_MATRIX_WAIT (A_in) ; GB_MATRIX_WAIT (B_in) ; //-------------------------------------------------------------------------- // bitmap case: create sparse copies of A and B if they are bitmap //-------------------------------------------------------------------------- GrB_Matrix A = A_in ; if (GB_IS_BITMAP (A)) { GBURBLE ("A:") ; GB_OK (GB_dup2 (&A2, A, true, A->type, Context)) ; // static header GB_OK (GB_convert_bitmap_to_sparse (A2, Context)) ; A = A2 ; } GrB_Matrix B = B_in ; if (GB_IS_BITMAP (B)) { GBURBLE ("B:") ; GB_OK (GB_dup2 (&B2, B, true, B->type, Context)) ; // static header GB_OK (GB_convert_bitmap_to_sparse (B2, Context)) ; B = B2 ; } //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; const int64_t *restrict Ai = A->i ; const GB_void *restrict Ax = A_is_pattern ? NULL : ((GB_void *) A->x) ; const int64_t asize = A->type->size ; const int64_t avlen = A->vlen ; const int64_t avdim = A->vdim ; int64_t anvec = A->nvec ; int64_t anz = GB_NNZ (A) ; const int64_t *restrict Bp = B->p ; const int64_t *restrict Bh = B->h ; const int64_t *restrict Bi = B->i ; const GB_void *restrict Bx = B_is_pattern ? NULL : ((GB_void *) B->x) ; const int64_t bsize = B->type->size ; const int64_t bvlen = B->vlen ; const int64_t bvdim = B->vdim ; int64_t bnvec = B->nvec ; int64_t bnz = GB_NNZ (B) ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- double work = ((double) anz) * ((double) bnz) + (((double) anvec) * ((double) bnvec)) ; GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (work, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // allocate the output matrix C //-------------------------------------------------------------------------- // C has the same type as z for the multiply operator, z=op(x,y) GrB_Index cvlen, cvdim, cnzmax, cnvec ; bool ok = GB_Index_multiply (&cvlen, avlen, bvlen) ; ok = ok & GB_Index_multiply (&cvdim, avdim, bvdim) ; ok = ok & GB_Index_multiply (&cnzmax, anz, bnz) ; ok = ok & GB_Index_multiply (&cnvec, anvec, bnvec) ; ASSERT (ok) ; // C is hypersparse if either A or B are hypersparse. It is never bitmap. bool C_is_hyper = (cvdim > 1) && (Ah != NULL || Bh != NULL) ; bool C_is_full = GB_is_dense (A) && GB_is_dense (B) ; int sparsity = C_is_full ? GxB_FULL : ((C_is_hyper) ? GxB_HYPERSPARSE : GxB_SPARSE) ; GB_OK (GB_new_bix (&C, true, // full, sparse, or hyper; static header op->ztype, (int64_t) cvlen, (int64_t) cvdim, GB_Ap_malloc, C_is_csc, sparsity, true, B->hyper_switch, cnvec, cnzmax, true, Context)) ; //-------------------------------------------------------------------------- // get C and the operator //-------------------------------------------------------------------------- int64_t *restrict Cp = C->p ; int64_t *restrict Ch = C->h ; int64_t *restrict Ci = C->i ; GB_void *restrict Cx = (GB_void *) C->x ; int64_t *restrict Cx_int64 = NULL ; int32_t *restrict Cx_int32 = NULL ; const int64_t csize = C->type->size ; GxB_binary_function fmult = op->function ; GB_Opcode opcode = op->opcode ; bool op_is_positional = GB_OPCODE_IS_POSITIONAL (opcode) ; GB_cast_function cast_A = NULL, cast_B = NULL ; if (!A_is_pattern) { cast_A = GB_cast_factory (op->xtype->code, A->type->code) ; } if (!B_is_pattern) { cast_B = GB_cast_factory (op->ytype->code, B->type->code) ; } int64_t offset = 0 ; if (op_is_positional) { offset = GB_positional_offset (opcode) ; Cx_int64 = (int64_t *) Cx ; Cx_int32 = (int32_t *) Cx ; } bool is64 = (op->ztype == GrB_INT64) ; //-------------------------------------------------------------------------- // compute the column counts of C, and C->h if C is hypersparse //-------------------------------------------------------------------------- int64_t kC ; if (!C_is_full) { #pragma omp parallel for num_threads(nthreads) schedule(guided) for (kC = 0 ; kC < cnvec ; kC++) { int64_t kA = kC / bnvec ; int64_t kB = kC % bnvec ; // get A(:,jA), the (kA)th vector of A int64_t jA = GBH (Ah, kA) ; int64_t aknz = (Ap == NULL) ? avlen : (Ap [kA+1] - Ap [kA]) ; // get B(:,jB), the (kB)th vector of B int64_t jB = GBH (Bh, kB) ; int64_t bknz = (Bp == NULL) ? bvlen : (Bp [kB+1] - Bp [kB]) ; // determine # entries in C(:,jC), the (kC)th vector of C // int64_t kC = kA * bnvec + kB ; if (!C_is_full) { Cp [kC] = aknz * bknz ; } if (C_is_hyper) { Ch [kC] = jA * bvdim + jB ; } } GB_cumsum (Cp, cnvec, &(C->nvec_nonempty), nthreads, Context) ; if (C_is_hyper) C->nvec = cnvec ; } C->magic = GB_MAGIC ; //-------------------------------------------------------------------------- // C = kron (A,B) //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(guided) for (kC = 0 ; kC < cnvec ; kC++) { int64_t kA = kC / bnvec ; int64_t kB = kC % bnvec ; // get B(:,jB), the (kB)th vector of B int64_t jB = GBH (Bh, kB) ; int64_t pB_start = GBP (Bp, kB, bvlen) ; int64_t pB_end = GBP (Bp, kB+1, bvlen) ; int64_t bknz = pB_start - pB_end ; if (bknz == 0) continue ; GB_void bwork [GB_VLA(bsize)] ; // get C(:,jC), the (kC)th vector of C // int64_t kC = kA * bnvec + kB ; int64_t pC = GBP (Cp, kC, cvlen) ; // get A(:,jA), the (kA)th vector of A int64_t jA = GBH (Ah, kA) ; int64_t pA_start = GBP (Ap, kA, avlen) ; int64_t pA_end = GBP (Ap, kA+1, avlen) ; GB_void awork [GB_VLA(asize)] ; for (int64_t pA = pA_start ; pA < pA_end ; pA++) { // awork = A(iA,jA), typecasted to op->xtype int64_t iA = GBI (Ai, pA, avlen) ; int64_t iAblock = iA * bvlen ; if (!A_is_pattern) cast_A (awork, Ax +(pA*asize), asize) ; for (int64_t pB = pB_start ; pB < pB_end ; pB++) { // bwork = B(iB,jB), typecasted to op->ytype int64_t iB = GBI (Bi, pB, bvlen) ; if (!B_is_pattern) cast_B (bwork, Bx +(pB*bsize), bsize) ; // C(iC,jC) = A(iA,jA) * B(iB,jB) if (!C_is_full) { int64_t iC = iAblock + iB ; Ci [pC] = iC ; } if (op_is_positional) { // positional binary operator switch (opcode) { case GB_FIRSTI_opcode : // z = first_i(A(iA,jA),y) == iA case GB_FIRSTI1_opcode : // z = first_i1(A(iA,jA),y) == iA+1 if (is64) { Cx_int64 [pC] = iA + offset ; } else { Cx_int32 [pC] = (int32_t) (iA + offset) ; } break ; case GB_FIRSTJ_opcode : // z = first_j(A(iA,jA),y) == jA case GB_FIRSTJ1_opcode : // z = first_j1(A(iA,jA),y) == jA+1 if (is64) { Cx_int64 [pC] = jA + offset ; } else { Cx_int32 [pC] = (int32_t) (jA + offset) ; } break ; case GB_SECONDI_opcode : // z = second_i(x,B(iB,jB)) == iB case GB_SECONDI1_opcode : // z = second_i1(x,B(iB,jB)) == iB+1 if (is64) { Cx_int64 [pC] = iB + offset ; } else { Cx_int32 [pC] = (int32_t) (iB + offset) ; } break ; case GB_SECONDJ_opcode : // z = second_j(x,B(iB,jB)) == jB case GB_SECONDJ1_opcode : // z = second_j1(x,B(iB,jB)) == jB+1 if (is64) { Cx_int64 [pC] = jB + offset ; } else { Cx_int32 [pC] = (int32_t) (jB + offset) ; } break ; default: ; } } else { // standard binary operator fmult (Cx +(pC*csize), awork, bwork) ; } pC++ ; } } } //-------------------------------------------------------------------------- // remove empty vectors from C, if hypersparse //-------------------------------------------------------------------------- GB_OK (GB_hypermatrix_prune (C, Context)) ; //-------------------------------------------------------------------------- // return result //-------------------------------------------------------------------------- ASSERT_MATRIX_OK (C, "C=kron(A,B)", GB0) ; GB_FREE_WORK ; return (GrB_SUCCESS) ; }
mafillpcompmain.c
/* CalculiX - A 3-dimensional finite element program */ /* Copyright (C) 1998-2015 Guido Dhondt */ /* 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(version 2); */ /* */ /* 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <unistd.h> #include <stdio.h> #include <math.h> #include <stdlib.h> #include <pthread.h> #include "CalculiX.h" static char *lakonf1; static ITG num_cpus,*nef1,*ipnei1,*neifa1,*neiel1,*jq1,*irow1,*ielfa1, *ifabou1,*neq1,*nzs1,*neij1,*ielmatf1,*mi1,*ntmat1_,*nactdohinv1; static double *vfa1,*area1,*advfa1,*xlet1,*cosa1,*volume1,*au1=NULL,*ad1=NULL, *ap1,*xle1,*b1=NULL,*xxn1,*hfa1,*gradpel1,*bp1,*xxi1,*xlen1,*cosb1, *a11,*a21,*a31,*velo1,*veloo1,*dtimef1,*shcon1,*vel1,*xrlfa1,*flux1; void mafillpcompmain(ITG *nef,char *lakonf,ITG *ipnei, ITG *neifa,ITG *neiel,double *vfa,double *area,double *advfa, double *xlet,double *cosa,double *volume,double *au,double *ad, ITG *jq,ITG *irow,double *ap,ITG *ielfa,ITG *ifabou, double *xle,double *b,double *xxn,ITG *neq, ITG *nzs,double *hfa,double *gradpel, double *bp,double *xxi,ITG *neij,double *xlen,double *cosb, ITG *ielmatf,ITG *mi,double *a1,double *a2,double *a3,double *velo, double *veloo,double *dtimef,double *shcon,ITG *ntmat_,double *vel, ITG *nactdohinv,double *xrlfa,double *flux){ ITG i,j; /* variables for multithreading procedure */ ITG sys_cpus,*ithread=NULL; char *env,*envloc,*envsys; num_cpus = 0; sys_cpus=0; /* explicit user declaration prevails */ envsys=getenv("NUMBER_OF_CPUS"); if(envsys){ sys_cpus=atoi(envsys); if(sys_cpus<0) sys_cpus=0; } /* automatic detection of available number of processors */ if(sys_cpus==0){ sys_cpus = getSystemCPUs(); if(sys_cpus<1) sys_cpus=1; } /* local declaration prevails, if strictly positive */ envloc = getenv("CCX_NPROC_CFD"); if(envloc){ num_cpus=atoi(envloc); if(num_cpus<0){ num_cpus=0; }else if(num_cpus>sys_cpus){ num_cpus=sys_cpus; } } /* else global declaration, if any, applies */ env = getenv("OMP_NUM_THREADS"); if(num_cpus==0){ if (env) num_cpus = atoi(env); if (num_cpus < 1) { num_cpus=1; }else if(num_cpus>sys_cpus){ num_cpus=sys_cpus; } } // next line is to be inserted in a similar way for all other paralell parts if(*nef<num_cpus) num_cpus=*nef; pthread_t tid[num_cpus]; /* allocating fields for lhs and rhs matrix */ NNEW(ad1,double,num_cpus**neq); NNEW(au1,double,(long long)num_cpus*2**nzs); NNEW(b1,double,num_cpus**neq); /* calculating the stiffness and/or mass matrix (symmetric part) */ nef1=nef;lakonf1=lakonf;ipnei1=ipnei;neifa1=neifa;neiel1=neiel; vfa1=vfa;area1=area;advfa1=advfa;xlet1=xlet,cosa1=cosa;volume1=volume; jq1=jq;irow1=irow;ap1=ap;ielfa1=ielfa;ifabou1=ifabou;xle1=xle; xxn1=xxn;neq1=neq;nzs1=nzs;hfa1=hfa;gradpel1=gradpel;bp1=bp;xxi1=xxi; neij1=neij;xlen1=xlen;cosb1=cosb;ielmatf1=ielmatf;mi1=mi,a11=a1; a21=a2;a31=a3;velo1=velo;veloo1=veloo;dtimef1=dtimef;shcon1=shcon; ntmat1_=ntmat_;vel1=vel;nactdohinv1=nactdohinv;xrlfa1=xrlfa; flux1=flux; /* create threads and wait */ NNEW(ithread,ITG,num_cpus); for(i=0; i<num_cpus; i++) { ithread[i]=i; pthread_create(&tid[i], NULL, (void *)mafillpcompmt, (void *)&ithread[i]); } for(i=0; i<num_cpus; i++) pthread_join(tid[i], NULL); SFREE(ithread); /* copying and accumulating the stiffnes and/or mass matrix */ #pragma omp parallel \ default(none) \ shared(neq,ad,ad1,num_cpus,nzs,au,au1,b,b1) \ private(i,j) { #pragma omp for for(i=0;i<*neq;i++){ ad[i]=ad1[i]; for(j=1;j<num_cpus;j++){ ad[i]+=ad1[i+j**neq]; } } #pragma omp for for(i=0;i<2**nzs;i++){ au[i]=au1[i]; for(j=1;j<num_cpus;j++){ au[i]+=au1[i+(long long)j*2**nzs]; } } #pragma omp for for(i=0;i<*neq;i++){ b[i]=b1[i]; for(j=1;j<num_cpus;j++){ b[i]+=b1[i+j**neq]; } } } SFREE(ad1); SFREE(au1); SFREE(b1); return; } /* subroutine for multithreading of mafillpcomp */ void *mafillpcompmt(ITG *i){ ITG indexad,indexb,nefa,nefb,nefdelta; long long indexau; indexad=*i**neq1; indexau=(long long)*i*2**nzs1; indexb=*i**neq1; // ceil -> floor nefdelta=(ITG)floor(*nef1/(double)num_cpus); nefa=*i*nefdelta+1; nefb=(*i+1)*nefdelta; // next line! -> all parallel sections if((*i==num_cpus-1)&&(nefb<*nef1)) nefb=*nef1; FORTRAN(mafillpcomp,(nef1,lakonf1,ipnei1,neifa1,neiel1,vfa1,area1, advfa1,xlet1,cosa1,volume1,&au1[indexau],&ad1[indexad], jq1,irow1,ap1,ielfa1,ifabou1,xle1,&b1[indexb],xxn1,neq1,nzs1, hfa1,gradpel1,bp1,xxi1,neij1,xlen1,cosb1,ielmatf1,mi1, a11,a21,a31,velo1,veloo1,dtimef1,shcon1,ntmat1_,vel1, nactdohinv1,xrlfa1,flux1,&nefa,&nefb)); return NULL; }
GB_unaryop__minv_int32_uint32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_int32_uint32 // op(A') function: GB_tran__minv_int32_uint32 // C type: int32_t // A type: uint32_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 32) #define GB_ATYPE \ uint32_t #define GB_CTYPE \ int32_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 = GB_IMINV_SIGNED (x, 32) ; // casting #define GB_CASTING(z, x) \ int32_t z = (int32_t) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT32 || GxB_NO_UINT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int32_uint32 ( int32_t *restrict Cx, const uint32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_int32_uint32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Network.h
/* * Network.h * * Created by Guido Novati on 30.10.18. * Copyright 2018 ETH Zurich. All rights reserved. * */ #pragma once #include "Layers.h" struct Network { std::mt19937 gen; // Vector of layers, each defines a forward and bckward operation: std::vector<Layer*> layers; // Vector of parameters of each layer (two vectors must have the same size) // Each Params contains the matrices of parameters needed by the corresp layer std::vector<Params*> params; // Vector of grads for each parameter. By definition they have the same size std::vector<Params*> grads; // Memory space where each layer can compute its output and gradient: std::vector<Activation*> workspace; // Number of inputs to the network: int nInputs = 0; // Number of network outputs: int nOutputs = 0; Network(const int seed = 0) : gen(seed) {}; std::vector<std::vector<Real>> forward( // one vector of input for each element in the mini-batch: const std::vector<std::vector<Real>> I, // layer ID at which to start forward operation: const size_t layerStart = 0 // (zero means compute from input to output) ) { if(params.size()==0 || grads.size()==0 || layers.size()==0) { printf("Attempted to access uninitialized network. Aborting\n"); abort(); } // input is a minibatch of datapoints: one vector for each datapoint: const size_t batchSize = I.size(); // allocate workspaces where we can write output of each layer clearWorkspace(); workspace = allocateActivation(batchSize); // User can overwrite the output of any upper layer (marked by layerStart) // in order to see what happens if layer layerStart has a predefined output. // ( this allows visualizing PCA components! ) const int inputLayerSize = workspace[layerStart]->layersSize; //copy input onto output of input layer: #pragma omp parallel for for (size_t b=0; b<batchSize; b++) { assert(I[b].size() == (size_t) inputLayerSize ); // Input to the network is the output of input layer. // Respective workspace is a matrix of size [batchSize]x[nInputs] // Here we use row-major ordering: nInputs is the number of columns. Real* const input_b = workspace[layerStart]->output + b * inputLayerSize; // copy from function argument to workspace: std::copy(I[b].begin(), I[b].end(), input_b); } // Start from layer after input. E.g. Input layer is 0. No need to backprop // input layer has it has no parameters. for (size_t j=layerStart+1; j<layers.size(); j++) layers[j]->forward(workspace, params); // copy output into vector of vectors: one vector for each element of batch std::vector<std::vector<Real>> O(batchSize, std::vector<Real>(nOutputs, 0)); #pragma omp parallel for for (size_t b=0; b<batchSize; b++) { assert(nOutputs == workspace.back()->layersSize); // network output is the output of last layer. // Respective workspace is a matrix of size [batchSize]x[nOutputs] // Here we use row-major ordering: nOutputs is the number of columns. Real* const output_b = workspace.back()->output + b * nOutputs; // copy from function argument to workspace: std::copy(output_b, output_b + nOutputs, O[b].begin()); } return O; } void bckward( // vector of size of mini-batch of gradients of error wrt to network output const std::vector<std::vector<Real>> E, // layer ID at which forward operation was started: const size_t layerStart=0 // (zero means compute from input to output) ) const { //this function assumes that we already called forward propagation if(params.size()==0 || grads.size()==0 || layers.size()==0) { printf("Attempted to access uninitialized network. Aborting\n"); abort(); } // input is a minibatch of datapoints: one vector for each datapoint: const size_t batchSize = E.size(); assert( (size_t) workspace.back()->batchSize == batchSize); // first, clear memory over which we'll write gradients: for(auto& p : workspace) p->clearErrors(); //copy input onto output of input layer: #pragma omp parallel for for (size_t b=0; b<batchSize; b++) { assert(E[b].size() == (size_t) nOutputs); // Write d Err / d Out onto last layer of the network. // Respective workspace is a matrix of size [batchSize]x[nOutputs] // Here we use row-major ordering: nOutputs is the number of columns. Real* const errors_b = workspace.back()->dError_dOutput + b * nOutputs; // copy from function argument to workspace: std::copy(E[b].begin(), E[b].end(), errors_b); } // Backprop starts at the last layer, which computes gradient of error wrt // to its parameters and gradient of error wrt to it's input. // Last layer to backprop is the one above input layer. Eg. if layerStart=0 // Then input layer was 0, which has no parametes and has no inputs to // backprp the error grad to, last layer to backprop is layer 1. for (size_t i = layers.size()-1; i >= layerStart + 1; i--) layers[i]->bckward(workspace, params, grads); } // Helper function for forward with batchsize = 1 std::vector<Real> forward(const std::vector<Real>I, const size_t layerStart=0) { std::vector<std::vector<Real>> vecI (1, I); std::vector<std::vector<Real>> vecO = forward(vecI, layerStart); return vecO[0]; } // Helper function for forward with batchsize = 1) void bckward(const std::vector<Real> E, const size_t layerStart = 0) const { std::vector<std::vector<Real>> vecE (1, E); bckward(vecE, layerStart); } void save() const { for(const auto &l : layers) l->save(params); } void restart() const { for(const auto &l : layers) l->restart(params); } ~Network() { for(auto& p : grads) _dispose_object(p); for(auto& p : params) _dispose_object(p); for(auto& p : layers) _dispose_object(p); for(auto& p : workspace) _dispose_object(p); } inline void clearWorkspace() { for(auto& p : workspace) _dispose_object(p); workspace.clear(); } // Function to loop over layers and allocate workspace for network operations: inline std::vector<Activation*> allocateActivation(size_t batchSize) const { std::vector<Activation*> ret(layers.size(), nullptr); for(size_t j=0; j<layers.size(); j++) ret[j] = layers[j]->allocateActivation(batchSize); return ret; } // Function to loop over layers and allocate memory space for parameter grads: inline std::vector<Params*> allocateGrad() const { std::vector<Params*> ret(layers.size(), nullptr); for(size_t j=0; j<layers.size(); j++) ret[j] = layers[j]->allocate_params(); return ret; } ////////////////////////////////////////////////////////////////////////////// /// Functions to build the network are defined in Network_buildFunctions.h /// ////////////////////////////////////////////////////////////////////////////// template<int size> void addInput(); template<int nInputs, int size> void addLinear(const std::string fname = std::string()); template<int size> void addTanh(); }; #include "Network_buildFunctions.h"
GB_unop__identity_int32_uint16.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_int32_uint16 // op(A') function: GB_unop_tran__identity_int32_uint16 // C type: int32_t // A type: uint16_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_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) \ int32_t z = (int32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = (int32_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int32_uint16 ( int32_t *Cx, // Cx and Ax may be aliased const uint16_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++) { uint16_t aij = Ax [p] ; int32_t z = (int32_t) aij ; Cx [p] = z ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_int32_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
SSSP.c
// ----------------------------------------------------------------------------- // // "00_AccelGraph" // // ----------------------------------------------------------------------------- // Copyright (c) 2014-2019 All rights reserved // ----------------------------------------------------------------------------- // Author : Abdullah Mughrabi // Email : atmughra@ncsu.edu||atmughrabi@gmail.com // File : SSSP.c // Create : 2019-06-21 17:15:17 // Revise : 2019-09-28 15:34:11 // Editor : Abdullah Mughrabi // ----------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <math.h> #include <omp.h> #include <limits.h> //UINT_MAX #include "timer.h" #include "myMalloc.h" #include "boolean.h" #include "arrayQueue.h" #include "bitmap.h" #include "sortRun.h" #include "reorder.h" #include "graphConfig.h" #include "graphCSR.h" #include "graphGrid.h" #include "graphAdjArrayList.h" #include "graphAdjLinkedList.h" #include "SSSP.h" // ******************************************************************************************** // *************** Stats DataStructure ************** // ******************************************************************************************** struct SSSPStats *newSSSPStatsGeneral(uint32_t num_vertices, uint32_t delta) { uint32_t v; struct SSSPStats *stats = (struct SSSPStats *) malloc(sizeof(struct SSSPStats)); stats->bucket_counter = 0; stats->delta = delta; stats->bucket_current = 0; stats->processed_nodes = 0; stats->buckets_total = 0; stats->time_total = 0.0; stats->num_vertices = num_vertices; stats->distances = (uint32_t *) my_malloc(num_vertices * sizeof(uint32_t)); stats->parents = (uint32_t *) my_malloc(num_vertices * sizeof(uint32_t)); stats->buckets_map = (uint32_t *) my_malloc(num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < num_vertices; v++) { stats->buckets_map[v] = UINT_MAX / 2; stats->distances[v] = UINT_MAX / 2; stats->parents[v] = UINT_MAX; } return stats; } struct SSSPStats *newSSSPStatsGraphCSR(struct GraphCSR *graph, uint32_t delta) { uint32_t v; struct SSSPStats *stats = (struct SSSPStats *) malloc(sizeof(struct SSSPStats)); stats->bucket_counter = 0; stats->delta = delta; stats->bucket_current = 0; stats->processed_nodes = 0; stats->buckets_total = 0; stats->time_total = 0.0; stats->num_vertices = graph->num_vertices; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->buckets_map = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->buckets_map[v] = UINT_MAX / 2; stats->distances[v] = UINT_MAX / 2; stats->parents[v] = UINT_MAX; } return stats; } struct SSSPStats *newSSSPStatsGraphGrid(struct GraphGrid *graph, uint32_t delta) { uint32_t v; struct SSSPStats *stats = (struct SSSPStats *) malloc(sizeof(struct SSSPStats)); stats->bucket_counter = 0; stats->delta = delta; stats->bucket_current = 0; stats->processed_nodes = 0; stats->buckets_total = 0; stats->time_total = 0.0; stats->num_vertices = graph->num_vertices; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->buckets_map = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->buckets_map[v] = UINT_MAX / 2; stats->distances[v] = UINT_MAX / 2; stats->parents[v] = UINT_MAX; } return stats; } struct SSSPStats *newSSSPStatsGraphAdjArrayList(struct GraphAdjArrayList *graph, uint32_t delta) { uint32_t v; struct SSSPStats *stats = (struct SSSPStats *) malloc(sizeof(struct SSSPStats)); stats->bucket_counter = 0; stats->delta = delta; stats->bucket_current = 0; stats->processed_nodes = 0; stats->buckets_total = 0; stats->time_total = 0.0; stats->num_vertices = graph->num_vertices; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->buckets_map = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->buckets_map[v] = UINT_MAX / 2; stats->distances[v] = UINT_MAX / 2; stats->parents[v] = UINT_MAX; } return stats; } struct SSSPStats *newSSSPStatsGraphAdjLinkedList(struct GraphAdjLinkedList *graph, uint32_t delta) { uint32_t v; struct SSSPStats *stats = (struct SSSPStats *) malloc(sizeof(struct SSSPStats)); stats->bucket_counter = 0; stats->delta = delta; stats->bucket_current = 0; stats->processed_nodes = 0; stats->buckets_total = 0; stats->time_total = 0.0; stats->num_vertices = graph->num_vertices; stats->distances = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->parents = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); stats->buckets_map = (uint32_t *) my_malloc(graph->num_vertices * sizeof(uint32_t)); #pragma omp parallel for for(v = 0; v < graph->num_vertices; v++) { stats->buckets_map[v] = UINT_MAX / 2; stats->distances[v] = UINT_MAX / 2; stats->parents[v] = UINT_MAX; } return stats; } void freeSSSPStats(struct SSSPStats *stats) { if(stats) { if(stats->distances) free(stats->distances); if(stats->parents) free(stats->parents); if(stats->buckets_map) free(stats->buckets_map); free(stats); } } // ******************************************************************************************** // *************** Auxiliary functions ************** // ******************************************************************************************** uint32_t SSSPAtomicMin(uint32_t *dist, uint32_t newValue) { uint32_t oldValue; uint32_t flag = 0; do { oldValue = *dist; if(oldValue > newValue) { if(__sync_bool_compare_and_swap(dist, oldValue, newValue)) { flag = 1; } } else { return 0; } } while(!flag); return 1; } uint32_t SSSPCompareDistanceArrays(struct SSSPStats *stats1, struct SSSPStats *stats2) { uint32_t v = 0; for(v = 0 ; v < stats1->num_vertices ; v++) { if(stats1->distances[v] != stats2->distances[v] && stats2->distances[v] != ( UINT_MAX / 2) ) { // printf("v %u s1 %u s2 %u \n",v,stats1->distances[v],stats2->distances[v]); // return 0; } // else if(stats1->distances[v] != UINT_MAX/2) } return 1; } int SSSPAtomicRelax(uint32_t src, uint32_t dest, float weight, struct SSSPStats *stats) { uint32_t oldParent, newParent; uint32_t oldDistanceV = UINT_MAX / 2; uint32_t oldDistanceU = UINT_MAX / 2; uint32_t newDistance = UINT_MAX / 2; uint32_t oldBucket = UINT_MAX / 2; uint32_t newBucket = UINT_MAX / 2; uint32_t flagu = 0; uint32_t flagv = 0; do { flagu = 0; flagv = 0; oldDistanceV = stats->distances[src]; oldDistanceU = stats->distances[dest]; oldParent = stats->parents[dest]; oldBucket = stats->buckets_map[dest]; newDistance = oldDistanceV + weight; if( oldDistanceU > newDistance ) { newParent = src; newDistance = oldDistanceV + weight; newBucket = newDistance / stats->delta; if(__sync_bool_compare_and_swap(&(stats->distances[src]), oldDistanceV, oldDistanceV)) { flagv = 1; } if(__sync_bool_compare_and_swap(&(stats->distances[dest]), oldDistanceU, newDistance) && flagv) { flagu = 1; } } else { return 0; } } while (!flagu); __sync_bool_compare_and_swap(&(stats->parents[dest]), oldParent, newParent); if(__sync_bool_compare_and_swap(&(stats->buckets_map[dest]), oldBucket, newBucket)) { if(oldBucket == UINT_MAX / 2) #pragma omp atomic update stats->buckets_total++; } if(__sync_bool_compare_and_swap(&(stats->bucket_current), newBucket, stats->bucket_current)) { stats->bucket_counter = 1; } return 1; } int SSSPRelax(uint32_t src, uint32_t dest, float weight, struct SSSPStats *stats) { uint32_t newDistance = stats->distances[src] + weight; uint32_t bucket = UINT_MAX / 2; if( stats->distances[dest] > newDistance ) { if(stats->buckets_map[dest] == UINT_MAX / 2) stats->buckets_total++; stats->distances[dest] = newDistance; stats->parents[dest] = src; bucket = newDistance / stats->delta; // if(stats->buckets_map[dest] > bucket) stats->buckets_map[dest] = bucket; if (bucket == stats->bucket_current) stats->bucket_counter = 1; return 1; } return 0; } void SSSPPrintStats(struct SSSPStats *stats) { uint32_t v; for(v = 0; v < stats->num_vertices; v++) { if(stats->distances[v] != UINT_MAX / 2) { printf("d %u \n", stats->distances[v]); } } } void SSSPPrintStatsDetails(struct SSSPStats *stats) { uint32_t v; uint32_t minDistance = UINT_MAX / 2; uint32_t maxDistance = 0; uint32_t numberOfDiscoverNodes = 0; #pragma omp parallel for reduction(max:maxDistance) reduction(+:numberOfDiscoverNodes) reduction(min:minDistance) for(v = 0; v < stats->num_vertices; v++) { if(stats->distances[v] != UINT_MAX / 2) { numberOfDiscoverNodes++; if(minDistance > stats->distances[v] && stats->distances[v] != 0) minDistance = stats->distances[v]; if(maxDistance < stats->distances[v]) maxDistance = stats->distances[v]; } } printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Min Dist", "Max Dist", " Discovered"); printf(" -----------------------------------------------------\n"); printf("| %-15u | %-15u | %-15u | \n", minDistance, maxDistance, numberOfDiscoverNodes); printf(" -----------------------------------------------------\n"); } // ******************************************************************************************** // *************** CSR DataStructure ************** // ******************************************************************************************** void SSSPSpiltGraphCSR(struct GraphCSR *graph, struct GraphCSR **graphPlus, struct GraphCSR **graphMinus, uint32_t delta) { // The first subset, Ef, contains all edges (vi, vj) such that i < j; the second, Eb, contains edges (vi, vj) such that i > j. //calculate the size of each edge array uint32_t edgesPlusCounter = 0; uint32_t edgesMinusCounter = 0; // uint32_t numVerticesPlusCounter = 0; // uint32_t numVerticesMinusCounter = 0; uint32_t e; float weight; // uint32_t src; // uint32_t dest; #pragma omp parallel for private(e,weight) shared(graph,delta) reduction(+:edgesPlusCounter,edgesMinusCounter) for(e = 0 ; e < graph->num_edges ; e++) { // src = graph->sorted_edges_array[e].src; // dest = graph->sorted_edges_array[e].dest; weight = 1; #if WEIGHTED weight = graph->sorted_edges_array->edges_array_weight[e]; #endif if(weight > delta) { edgesPlusCounter++; } else if (weight <= delta) { edgesMinusCounter++; } } *graphPlus = graphCSRNew(graph->num_vertices, edgesPlusCounter, 1); *graphMinus = graphCSRNew(graph->num_vertices, edgesMinusCounter, 1); struct EdgeList *edgesPlus = newEdgeList(edgesPlusCounter); struct EdgeList *edgesMinus = newEdgeList(edgesMinusCounter); #if DIRECTED struct EdgeList *edgesPlusInverse = newEdgeList(edgesPlusCounter); struct EdgeList *edgesMinusInverse = newEdgeList(edgesMinusCounter); #endif uint32_t edgesPlus_idx = 0; uint32_t edgesMinus_idx = 0; #pragma omp parallel for private(e,weight) shared(edgesMinus_idx,edgesPlus_idx,edgesPlus,edgesMinus,graph) for(e = 0 ; e < graph->num_edges ; e++) { weight = 1; #if WEIGHTED weight = graph->sorted_edges_array->edges_array_weight[e]; #endif uint32_t index = 0; if(weight > delta) { index = __sync_fetch_and_add(&edgesPlus_idx, 1); edgesPlus->edges_array_dest[index] = graph->sorted_edges_array->edges_array_dest[e]; edgesPlus->edges_array_src[index] = graph->sorted_edges_array->edges_array_src[e]; #if WEIGHTED edgesPlus->edges_array_weight[index] = graph->sorted_edges_array->edges_array_weight[e]; #endif #if DIRECTED edgesPlusInverse->edges_array_dest[index] = graph->sorted_edges_array->edges_array_src[e]; edgesPlusInverse->edges_array_src[index] = graph->sorted_edges_array->edges_array_dest[e]; #if WEIGHTED edgesPlusInverse->edges_array_weight[index] = graph->sorted_edges_array->edges_array_weight[e]; #endif #endif } else if (weight <= delta) { index = __sync_fetch_and_add(&edgesMinus_idx, 1); edgesMinus->edges_array_dest[index] = graph->sorted_edges_array->edges_array_dest[e]; edgesMinus->edges_array_src[index] = graph->sorted_edges_array->edges_array_src[e]; #if WEIGHTED edgesMinus->edges_array_weight[index] = graph->sorted_edges_array->edges_array_weight[e]; #endif #if DIRECTED edgesMinusInverse->edges_array_dest[index] = graph->sorted_edges_array->edges_array_src[e]; edgesMinusInverse->edges_array_src[index] = graph->sorted_edges_array->edges_array_dest[e]; #if WEIGHTED edgesMinusInverse->edges_array_weight[index] = graph->sorted_edges_array->edges_array_weight[e]; #endif #endif } } edgesPlus = sortRunAlgorithms(edgesPlus, 0); edgesMinus = sortRunAlgorithms(edgesMinus, 0); #if DIRECTED edgesPlusInverse = sortRunAlgorithms(edgesPlusInverse, 0); edgesMinusInverse = sortRunAlgorithms(edgesMinusInverse, 0); #endif graphCSRAssignEdgeList ((*graphPlus), edgesPlus, 0); graphCSRAssignEdgeList ((*graphMinus), edgesMinus, 0); #if DIRECTED graphCSRAssignEdgeList ((*graphPlus), edgesPlusInverse, 1); graphCSRAssignEdgeList ((*graphMinus), edgesMinusInverse, 1); #endif } int test_13(int x) { int *i; i = &x; *i = x + 1; return x; } struct SSSPStats *SSSPGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { struct SSSPStats *stats = NULL; arguments->source = graph->sorted_edges_array->label_array[arguments->source]; switch (arguments->pushpull) { case 0: // push stats = SSSPDataDrivenPushGraphCSR(arguments, graph); // SSSPDataDrivenPullGraphCSR(arguments, graph); BUGGY break; case 1: // push stats = SSSPDataDrivenSplitPushGraphCSR(arguments, graph); break; default:// push stats = SSSPDataDrivenPushGraphCSR(arguments, graph); break; } return stats; } struct SSSPStats *SSSPDataDrivenPushGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { uint32_t v; uint32_t iter = 0; struct SSSPStats *stats = newSSSPStatsGraphCSR(graph, arguments->delta); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting Delta-Stepping Algorithm Push DD (Source)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct Bitmap *bitmapSetCurr = newBitmap(graph->num_vertices); uint32_t activeVertices = 0; printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Active vertices", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); Start(timer); Start(timer_inner); //order vertices according to degree stats->parents[arguments->source] = arguments->source; stats->distances[arguments->source] = 0; stats->buckets_map[arguments->source] = 0; // maps to bucket zero stats->bucket_counter = 1; stats->buckets_total = 1; stats->bucket_current = 0; activeVertices = 1; Stop(timer_inner); printf("| %-15s | %-15u | %-15f | \n", "Init", stats->buckets_total, Seconds(timer_inner)); printf(" -----------------------------------------------------\n"); while (stats->buckets_total) { // Start(timer_inner); stats->processed_nodes += activeVertices; activeVertices = 0; stats->bucket_counter = 1; clearBitmap(bitmapSetCurr); Start(timer_inner); while(stats->bucket_counter) { Start(timer_inner); stats->bucket_counter = 0; // uint32_t buckets_total_local = // process light edges #pragma omp parallel for private(v) shared(bitmapSetCurr, graph, stats) reduction(+ : activeVertices) for(v = 0; v < graph->num_vertices; v++) { if(__sync_bool_compare_and_swap(&(stats->buckets_map[v]), stats->bucket_current, (UINT_MAX / 2))) { // if(stats->buckets_map[v] == stats->bucket_current) { // pop vertex from bucket list setBitAtomic(bitmapSetCurr, v); #pragma omp atomic update stats->buckets_total--; // stats->buckets_map[v] = UINT_MAX/2; uint32_t degree = graph->vertices->out_degree[v]; uint32_t edge_idx = graph->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + degree) ; j++) { uint32_t src = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_src[j]); uint32_t dest = EXTRACT_VALUE(graph->sorted_edges_array->edges_array_dest[j]); float weight = 1; #if WEIGHTED weight = graph->sorted_edges_array->edges_array_weight[j]; #endif if(arguments->algo_numThreads == 1) activeVertices += SSSPRelax(src, dest, weight, stats); else activeVertices += SSSPAtomicRelax(src, dest, weight, stats); } } } Stop(timer_inner); if(activeVertices) printf("| L%-14u | %-15u | %-15f |\n", iter, stats->buckets_total, Seconds(timer_inner)); } iter++; stats->bucket_current++; Stop(timer_inner); if(activeVertices) printf("| H%-14u | %-15u | %-15f |\n", iter, stats->buckets_total, Seconds(timer_inner)); } Stop(timer); stats->time_total += Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); SSSPPrintStatsDetails(stats); // free resources free(timer); free(timer_inner); freeBitmap(bitmapSetCurr); // SSSPPrintStats(stats); return stats; } struct SSSPStats *SSSPDataDrivenSplitPushGraphCSR(struct Arguments *arguments, struct GraphCSR *graph) { uint32_t v; uint32_t iter = 0; struct SSSPStats *stats = newSSSPStatsGraphCSR(graph, arguments->delta); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Starting Delta-Stepping Algorithm Push DD (Source)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", arguments->source); if(arguments->source > graph->num_vertices) { printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "ERROR!! CHECK SOURCE RANGE"); printf(" -----------------------------------------------------\n"); return stats; } struct Timer *timer = (struct Timer *) malloc(sizeof(struct Timer)); struct Timer *timer_inner = (struct Timer *) malloc(sizeof(struct Timer)); struct Bitmap *bitmapSetCurr = newBitmap(graph->num_vertices); uint32_t activeVertices = 0; struct GraphCSR *graphHeavy = NULL; struct GraphCSR *graphLight = NULL; printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Start Split Heavy/Light"); printf(" -----------------------------------------------------\n"); Start(timer_inner); SSSPSpiltGraphCSR(graph, &graphHeavy, &graphLight, stats->delta); Stop(timer_inner); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Graph Light Edges (Number)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", graphLight->num_edges ); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "Graph Heavy Edges (Number)"); printf(" -----------------------------------------------------\n"); printf("| %-51u | \n", graphHeavy->num_edges); printf(" -----------------------------------------------------\n"); printf("| %-51s | \n", "END Split Heavy/Light"); printf(" -----------------------------------------------------\n"); printf("| %-51f | \n", Seconds(timer_inner)); printf(" -----------------------------------------------------\n"); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15s | %-15s | \n", "Iteration", "Active vertices", "Time (Seconds)"); printf(" -----------------------------------------------------\n"); Start(timer); Start(timer_inner); //order vertices according to degree stats->parents[arguments->source] = arguments->source; stats->distances[arguments->source] = 0; stats->buckets_map[arguments->source] = 0; // maps to bucket zero stats->bucket_counter = 1; stats->buckets_total = 1; stats->bucket_current = 0; activeVertices = 1; Stop(timer_inner); printf("| %-15s | %-15u | %-15f | \n", "Init", stats->buckets_total, Seconds(timer_inner)); printf(" -----------------------------------------------------\n"); while (stats->buckets_total) { // Start(timer_inner); stats->processed_nodes += activeVertices; activeVertices = 0; stats->bucket_counter = 1; clearBitmap(bitmapSetCurr); while(stats->bucket_counter) { Start(timer_inner); stats->bucket_counter = 0; // uint32_t buckets_total_local = // process light edges #pragma omp parallel for private(v) shared(bitmapSetCurr, graphLight, stats) reduction(+ : activeVertices) for(v = 0; v < graphLight->num_vertices; v++) { if(__sync_bool_compare_and_swap(&(stats->buckets_map[v]), stats->bucket_current, (UINT_MAX / 2))) { // if(stats->buckets_map[v] == stats->bucket_current) { // pop vertex from bucket list setBitAtomic(bitmapSetCurr, v); #pragma omp atomic update stats->buckets_total--; // stats->buckets_map[v] = UINT_MAX/2; uint32_t degree = graphLight->vertices->out_degree[v]; uint32_t edge_idx = graphLight->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + degree) ; j++) { uint32_t src = EXTRACT_VALUE(graphLight->sorted_edges_array->edges_array_src[j]); uint32_t dest = EXTRACT_VALUE(graphLight->sorted_edges_array->edges_array_dest[j]); float weight = 1; #if WEIGHTED weight = graphLight->sorted_edges_array->edges_array_weight[j]; #endif if(arguments->algo_numThreads == 1) activeVertices += SSSPRelax(src, dest, weight, stats); else activeVertices += SSSPAtomicRelax(src, dest, weight, stats); } } } Stop(timer_inner); if(activeVertices) printf("| L%-14u | %-15u | %-15f |\n", iter, stats->buckets_total, Seconds(timer_inner)); } Start(timer_inner); #pragma omp parallel for private(v) shared(bitmapSetCurr, graphHeavy, stats) reduction(+ : activeVertices) for(v = 0; v < graphHeavy->num_vertices; v++) { if(getBit(bitmapSetCurr, v)) { uint32_t degree = graphHeavy->vertices->out_degree[v]; uint32_t edge_idx = graphHeavy->vertices->edges_idx[v]; uint32_t j; for(j = edge_idx ; j < (edge_idx + degree) ; j++) { uint32_t src = EXTRACT_VALUE(graphHeavy->sorted_edges_array->edges_array_src[j]); uint32_t dest = EXTRACT_VALUE(graphHeavy->sorted_edges_array->edges_array_dest[j]); float weight = 1; #if WEIGHTED weight = graphHeavy->sorted_edges_array->edges_array_weight[j]; #endif if(arguments->algo_numThreads == 1) activeVertices += SSSPRelax(src, dest, weight, stats); else activeVertices += SSSPAtomicRelax(src, dest, weight, stats); } } } iter++; stats->bucket_current++; Stop(timer_inner); if(activeVertices) printf("| H%-14u | %-15u | %-15f |\n", iter, stats->buckets_total, Seconds(timer_inner)); } Stop(timer); stats->time_total += Seconds(timer); printf(" -----------------------------------------------------\n"); printf("| %-15s | %-15u | %-15f | \n", "total", stats->processed_nodes, stats->time_total); printf(" -----------------------------------------------------\n"); SSSPPrintStatsDetails(stats); // free resources free(timer); free(timer_inner); freeBitmap(bitmapSetCurr); graphCSRFree(graphHeavy); graphCSRFree(graphLight); // SSSPPrintStats(stats); return stats; }
GB_unaryop__minv_fp64_fp64.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_fp64_fp64 // op(A') function: GB_tran__minv_fp64_fp64 // C type: double // A type: double // cast: double cij = (double) aij // unaryop: cij = 1./aij #define GB_ATYPE \ double #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1./x ; // casting #define GB_CASTING(z, aij) \ double z = (double) 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_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_fp64_fp64 ( double *Cx, // Cx and Ax may be aliased double *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_fp64_fp64 ( 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
minusminus-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. */ // The -- operation on numNodes2 is not protected, causing data race. #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int len=100; int numNodes=len, numNodes2=0; int x[100]; // initialize x[] for (i=0; i< len; i++) { if (i%2==0) x[i]=5; else x[i]= -5; } #pragma omp parallel for for (i=numNodes-1 ; i>-1 ; --i) { if (x[i]<=0) { numNodes2-- ; } } printf ("numNodes2 = %d\n", numNodes2); return 0; }
omp_taskwait.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <math.h> #include "omp_testsuite.h" #include "omp_my_sleep.h" int test_omp_taskwait() { int result1 = 0; /* Stores number of not finished tasks after the taskwait */ int result2 = 0; /* Stores number of wrong array elements at the end */ int array[NUM_TASKS]; int i; /* fill array */ for (i = 0; i < NUM_TASKS; i++) array[i] = 0; #pragma omp parallel { #pragma omp single { for (i = 0; i < NUM_TASKS; i++) { /* First we have to store the value of the loop index in a new variable * which will be private for each task because otherwise it will be overwritten * if the execution of the task takes longer than the time which is needed to * enter the next step of the loop! */ int myi; myi = i; #pragma omp task { my_sleep (SLEEPTIME); array[myi] = 1; } /* end of omp task */ } /* end of for */ #pragma omp taskwait /* check if all tasks were finished */ for (i = 0; i < NUM_TASKS; i++) if (array[i] != 1) result1++; /* generate some more tasks which now shall overwrite * the values in the tids array */ for (i = 0; i < NUM_TASKS; i++) { int myi; myi = i; #pragma omp task { array[myi] = 2; } /* end of omp task */ } /* end of for */ } /* end of single */ } /*end of parallel */ /* final check, if all array elements contain the right values: */ for (i = 0; i < NUM_TASKS; i++) { if (array[i] != 2) result2++; } return ((result1 == 0) && (result2 == 0)); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_taskwait()) { num_failed++; } } return num_failed; }
scatmat.c
#include <stdlib.h> #include <complex.h> #include <float.h> #include <math.h> #include <string.h> #ifdef _MACOSX #include <Accelerate/Accelerate.h> #else #include <cblas.h> #endif #include "fastsphere.h" #include "spreflect.h" #include "translator.h" #include "scatmat.h" #include "fsht.h" #include "farfield.h" #include "util.h" /* Reflect incoming plane waves from the surfaces of all spheres. */ int sprflpw (complex double *rhs, spscat *spl, int nsph, shdata *shtr) { int i, nterm; complex double *vptr; spscat *sp; nterm = shtr->ntheta * shtr->nphi; #pragma omp parallel for private(i,vptr,sp) default(shared) for (i = 0; i < nsph; ++i) { sp = spl + i; vptr = rhs + i * nterm; /* Multiply by the reflection coefficient in SH space. */ ffsht (vptr, shtr, sp->spdesc->deg); spreflect (vptr, vptr, (spl + i)->spdesc->reflect, sp->spdesc->deg, shtr->nphi, 0, 1); ifsht (vptr, shtr, sp->spdesc->deg); } return nsph; } /* Compute translations between all spheres. Augments the output vector, does * not overwrite it. */ int sptrans (complex double *vout, complex double *vin, int nsph, trdesc *trans, shdata *shtr) { int nterm, nsq; nterm = shtr->ntheta * shtr->nphi; nsq = nsph * nsph; /* Perform the translations. */ #pragma omp parallel default(shared) { complex double *voptr, *viptr; int i, j, off, k; #pragma omp for for (off = 0; off < nsq; ++off) { j = off / nsph; /* Source sphere. */ i = off % nsph; /* Destination sphere. */ /* Don't bother with self-translations. Also ignore dense * translations for the moment. */ if (i == j || trans[off].type != TRPLANE) continue; /* Do the diagonal, plane-wave translation. */ voptr = vout + i * nterm; viptr = vin + j * nterm; /* Copy to output, but only one thread at a time. */ #pragma omp critical(outplane) for (k = 0; k < nterm; ++k) voptr[k] += trans[off].trdata[k] * viptr[k]; } } return nsph; } /* Compute the MVP between the scattering matrix and a specified vector. */ int scatmat (complex double *vout, complex double *vin, spscat *spl, int nsph, trdesc *trans, shdata *shtr) { int nterm, n, i; nterm = shtr->ntheta * shtr->nphi; n = nterm * nsph; /* Initialize the output bufer. */ memset (vout, 0, n * sizeof(complex double)); /* Compute the spherical translations. */ sptrans (vout, vin, nsph, trans, shtr); /* Compute the reflections of plane waves at sphere surfaces. */ sprflpw (vout, spl, nsph, shtr); /* Subtract the incoming field from the outgoing field. */ #pragma omp parallel for private(i) default(shared) for (i = 0; i < n; ++i) vout[i] = vin[i] - vout[i]; return nsph; } int bicgstab (complex double *sol, complex double *rhs, int guess, spscat *spl, int nsph, trdesc *trans, shdata *shtr, itconf *itc) { int i, j, n, nterm; complex double *r, *rhat, *v, *p, *t; complex double rho, alpha, omega, beta; double err, rhn; nterm = shtr->ntheta * shtr->nphi; n = nterm * nsph; rho = alpha = omega = 1.; /* Allocate and zero the work arrays. */ r = calloc (5 * n, sizeof(complex double)); rhat = r + n; v = rhat + n; p = v + n; t = p + n; /* Compute the norm of the right-hand side for residual scaling. */ rhn = cblas_dznrm2 (n, rhs, 1); /* Compute the inital matrix-vector product for the input guess. */ if (guess) scatmat (r, sol, spl, nsph, trans, shtr); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) r[j] = rhs[j] - r[j]; if (!guess) memset (sol, 0, n * sizeof(complex double)); /* Copy the initial residual as the test vector. */ memcpy (rhat, r, n * sizeof(complex double)); /* Find the norm of the initial residual. */ err = cblas_dznrm2(n, r, 1) / rhn; printf ("True residual: %g\n", err); /* Run iterations until convergence or the maximum is reached. */ for (i = 0; i < itc->iter && err > itc->eps; ++i) { /* Pre-compute portion of beta from previous iteration. */ beta = alpha / (rho * omega); /* Compute rho for this iteration. */ rho = pardot (rhat, r, n); /* Include the missing factor in beta. */ beta *= rho; /* Update the search vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) p[j] = r[j] + beta * (p[j] - omega * v[j]); /* Compute the first search step, v = A * p. */ scatmat (v, p, spl, nsph, trans, shtr); /* Compute the next alpha. */ alpha = rho / pardot (rhat, v, n); #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) { /* Update the solution vector. */ sol[j] += alpha * p[j]; /* Update the residual vector. */ r[j] -= alpha * v[j]; } /* Compute the scaled residual norm and stop if convergence * has been achieved. */ err = cblas_dznrm2 (n, r, 1) / rhn; printf ("BiCG-STAB(%0.1f): %g\n", 0.5 + i, err); if (err < itc->eps) break; /* Compute the next search step, t = A * r. */ scatmat (t, r, spl, nsph, trans, shtr); /* Compute the update direction. */ omega = pardot (t, r, n) / pardot (t, t, n); /* Update both the residual and the solution guess. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) { /* Update the solution vector. */ sol[j] += omega * r[j]; /* Update the residual vector. */ r[j] -= omega * t[j]; } /* Compute the scaled residual norm. */ err = cblas_dznrm2 (n, r, 1) / rhn; printf ("BiCG-STAB(%d): %g\n", i + 1, err); } free (r); return i; } int gmres (complex double *sol, complex double *rhs, int guess, spscat *spl, int nsph, trdesc *trans, shdata *shtr, itconf *itc) { int nterm = shtr->ntheta * shtr->nphi, n = nterm * nsph; long lwork; int i, j, one = 1, mit = itc->iter; complex double *h, *v, *beta, *y; complex double *vp, *hp, *s, cr, cone = 1.; double rhn, err, *c; /* Allocate space for all required complex vectors. */ lwork = (mit + 1) * (mit + n + 1) + mit; v = calloc (lwork, sizeof(complex double)); /* The Krylov subspace. */ beta = v + n * (mit + 1); /* The least-squares RHS. */ h = beta + mit + 1; /* The upper Hessenberg matrix. */ s = h + (mit + 1) * mit; /* Givens rotation sines. */ /* Allocate space for the Givens rotation cosines. */ c = malloc (mit * sizeof(double)); /* Compute the norm of the RHS for residual scaling. */ rhn = cblas_dznrm2 (n, rhs, 1); /* Compute the initial matrix-vector product for the input guess. */ if (guess) scatmat (v, sol, spl, nsph, trans, shtr); /* Subtract from the RHS to form the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] = rhs[j] - v[j]; /* Zero the initial guess if one wasn't provided. */ if (!guess) memset (sol, 0, n * sizeof(complex double)); /* Find the norm of the initial residual. */ err = cblas_dznrm2(n, v, 1); /* Construct the initial Arnoldi vector by normalizing the residual. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) v[j] /= err; /* Construct the vector beta for the minimization problem. */ beta[0] = err; /* Report the RRE. */ err /= rhn; printf ("True residual: %g\n", err); for (i = 0; i < mit && err > itc->eps; ++i) { /* Point to the working space for this iteration. */ vp = v + i * n; hp = h + i * (mit + 1); /* Compute the next expansion of the Krylov space. */ scatmat (vp + n, vp, spl, nsph, trans, shtr); /* Perform modified Gram-Schmidt to orthogonalize the basis. */ /* This also builds the Hessenberg matrix column. */ cmgs (vp + n, hp, v, n, i + 1); /* Compute the norm of the next basis vector. */ hp[i + 1] = cblas_dznrm2(n, vp + n, 1); /* Avoid breakdown. */ if (cabs(hp[i + 1]) < DBL_EPSILON) { ++i; break; } /* Normalize the basis vector. */ #pragma omp parallel for default(shared) private(j) for (j = 0; j < n; ++j) vp[n + j] /= creal(hp[i + 1]); /* Apply previous Givens rotations to the Hessenberg column. */ for (j = 0; j < i; ++j) zrot_ (&one, (void *)(hp + j), &one, (void *)(hp + j + 1), &one, (void *)(c + j), (void *)(s + j)); /* Compute the Givens rotation for the current iteration. */ zlartg_ ((void *)(hp + i), (void *)(hp + i + 1), (void *)(c + i), (void *)(s + i), (void *)(&cr)); /* Apply the current Givens rotation to the Hessenberg column. */ hp[i] = cr; hp[i + 1] = 0; /* Perform the rotation on the vector beta. */ zrot_ (&one, (void *)(beta + i), &one, (void *)(beta + i + 1), &one, (void *)(c + i), (void *)(s + i)); /* Estimate the RRE for this iteration. */ err = cabs(beta[i + 1]) / rhn; printf ("GMRES(%d): %g\n", i, err); } /* If there were any GMRES iterations, update the solution. */ if (i > 0) { /* Compute the minimizer of the least-squares problem. */ cblas_ztrsv (CblasColMajor, CblasUpper, CblasNoTrans, CblasNonUnit, i, h, mit + 1, beta, 1); /* Compute the update to the solution. */ cblas_zgemv (CblasColMajor, CblasNoTrans, n, i, &cone, v, n, beta, 1, &cone, sol, 1); } free (v); free (c); return i; }
segment.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS EEEEE GGGG M M EEEEE N N TTTTT % % SS E G MM MM E NN N T % % SSS EEE G GGG M M M EEE N N N T % % SS E G G M M E N NN T % % SSSSS EEEEE GGGG M M EEEEE N N T % % % % % % MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means % % % % Software Design % % Cristy % % April 1993 % % % % % % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segment segments an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % c-means technique. The scale-space filter analyzes the histograms of % the three color components of the image and identifies a set of % classes. The extents of each class is used to coarsely segment the % image with thresholding. The color associated with each class is % determined by the mean color of all pixels within the extents of a % particular class. Finally, any unclassified pixels are assigned to % the closest class with the fuzzy c-means technique. % % The fuzzy c-Means algorithm can be summarized as follows: % % o Build a histogram, one for each color component of the image. % % o For each histogram, successively apply the scale-space filter and % build an interval tree of zero crossings in the second derivative % at each scale. Analyze this scale-space ''fingerprint'' to % determine which peaks and valleys in the histogram are most % predominant. % % o The fingerprint defines intervals on the axis of the histogram. % Each interval contains either a minima or a maxima in the original % signal. If each color component lies within the maxima interval, % that pixel is considered ''classified'' and is assigned an unique % class number. % % o Any pixel that fails to be classified in the above thresholding % pass is classified using the fuzzy c-Means technique. It is % assigned to one of the classes discovered in the histogram analysis % phase. % % The fuzzy c-Means technique attempts to cluster a pixel by finding % the local minima of the generalized within group sum of squared error % objective function. A pixel is assigned to the closest class of % which the fuzzy membership has a maximum value. % % Segment is strongly based on software written by Andy Gallo, % University of Delaware. % % The following reference was used in creating this program: % % Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation % Algorithm Based on the Thresholding and the Fuzzy c-Means % Techniques", Pattern Recognition, Volume 23, Number 9, pages % 935-952, 1990. % % */ #include "MagickCore/studio.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/colormap.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #define MaxDimension 3 #define DeltaTau 0.5f #if defined(FastClassify) #define WeightingExponent 2.0 #define SegmentPower(ratio) (ratio) #else #define WeightingExponent 2.5 #define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0))); #endif #define Tau 5.2f /* Typedef declarations. */ typedef struct _ExtentPacket { double center; ssize_t index, left, right; } ExtentPacket; typedef struct _Cluster { struct _Cluster *next; ExtentPacket red, green, blue; ssize_t count, id; } Cluster; typedef struct _IntervalTree { double tau; ssize_t left, right; double mean_stability, stability; struct _IntervalTree *sibling, *child; } IntervalTree; typedef struct _ZeroCrossing { double tau, histogram[256]; short crossings[256]; } ZeroCrossing; /* Constant declarations. */ static const int Blue = 2, Green = 1, Red = 0, SafeMargin = 3, TreeLength = 600; /* Method prototypes. */ static double OptimalTau(const ssize_t *,const double,const double,const double, const double,short *); static ssize_t DefineRegion(const short *,ExtentPacket *); static void FreeNodes(IntervalTree *), InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *), ScaleSpace(const ssize_t *,const double,double *), ZeroCrossHistogram(double *,const double,short *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Classify() defines one or more classes. Each pixel is thresholded to % determine which class it belongs to. If the class is not identified it is % assigned to the closest class based on the fuzzy c-Means technique. % % The format of the Classify method is: % % MagickBooleanType Classify(Image *image,short **extrema, % const double cluster_threshold,const double weighting_exponent, % const MagickBooleanType verbose,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o weighting_exponent: Specifies the membership weighting exponent. % % o verbose: A value greater than zero prints detailed information about % the identified classes. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType Classify(Image *image,short **extrema, const double cluster_threshold,const double weighting_exponent, const MagickBooleanType verbose,ExceptionInfo *exception) { #define SegmentImageTag "Segment/Image" #define ThrowClassifyException(severity,tag,label) \ {\ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) \ { \ next_cluster=cluster->next; \ cluster=(Cluster *) RelinquishMagickMemory(cluster); \ } \ if (squares != (double *) NULL) \ { \ squares-=255; \ free_squares=squares; \ free_squares=(double *) RelinquishMagickMemory(free_squares); \ } \ ThrowBinaryException(severity,tag,label); \ } CacheView *image_view; Cluster *cluster, *head, *last_cluster, *next_cluster; double *free_squares; ExtentPacket blue, green, red; MagickOffsetType progress; MagickStatusType status; ssize_t i; double *squares; size_t number_clusters; ssize_t count, y; /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; squares=(double *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireQuantumMemory(1, sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ (void) memset(cluster,0,sizeof(*cluster)); cluster->red=red; cluster->green=green; cluster->blue=blue; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster)); if (cluster == (Cluster *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ (void) memset(cluster,0,sizeof(*cluster)); cluster->red=red; cluster->green=green; cluster->blue=blue; head=cluster; } /* Count the pixels for each cluster. */ status=MagickTrue; count=0; progress=0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *p; ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; pixel.red=(double) ScaleQuantumToChar(GetPixelRed(image,p)); pixel.green=(double) ScaleQuantumToChar(GetPixelGreen(image,p)); pixel.blue=(double) ScaleQuantumToChar(GetPixelBlue(image,p)); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if ((pixel.red >= (double) (cluster->red.left-SafeMargin)) && (pixel.red <= (double) (cluster->red.right+SafeMargin)) && (pixel.green >= (double) (cluster->green.left-SafeMargin)) && (pixel.green <= (double) (cluster->green.right+SafeMargin)) && (pixel.blue >= (double) (cluster->blue.left-SafeMargin)) && (pixel.blue <= (double) (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=pixel.red; cluster->green.center+=pixel.green; cluster->blue.center+=pixel.blue; cluster->count++; break; } p+=GetPixelChannels(image); } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } number_clusters=(size_t) count; if (verbose != MagickFalse) { /* Print cluster statistics. */ (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n"); (void) FormatLocaleFile(stdout,"===================\n\n"); (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double) cluster_threshold); (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double) weighting_exponent); (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n", (double) number_clusters); /* Print the total number of points per cluster. */ (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n"); (void) FormatLocaleFile(stdout,"=============================\n\n"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double) cluster->id,(double) cluster->count); /* Print the cluster extents. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"================"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout, "%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double) cluster->red.left,(double) cluster->red.right,(double) cluster->green.left,(double) cluster->green.right,(double) cluster->blue.left,(double) cluster->blue.right); } /* Print the cluster center values. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"====================="); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout,"%g %g %g\n",(double) cluster->red.center,(double) cluster->green.center,(double) cluster->blue.center); } (void) FormatLocaleFile(stdout,"\n"); } if (number_clusters > 256) ThrowClassifyException(ImageError,"TooManyClusters",image->filename); /* Speed up distance calculations. */ squares=(double *) AcquireQuantumMemory(513UL,sizeof(*squares)); if (squares == (double *) NULL) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); squares+=255; for (i=(-255); i <= 255; i++) squares[i]=(double) i*(double) i; /* Allocate image colormap. */ if (AcquireImageColormap(image,number_clusters,exception) == MagickFalse) ThrowClassifyException(ResourceLimitError,"MemoryAllocationFailed", image->filename); i=0; for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { image->colormap[i].red=(double) ScaleCharToQuantum((unsigned char) (cluster->red.center+0.5)); image->colormap[i].green=(double) ScaleCharToQuantum((unsigned char) (cluster->green.center+0.5)); image->colormap[i].blue=(double) ScaleCharToQuantum((unsigned char) (cluster->blue.center+0.5)); i++; } /* Do course grain classes. */ image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Cluster *c; const PixelInfo *magick_restrict p; ssize_t x; Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { PixelInfo pixel; SetPixelIndex(image,(Quantum) 0,q); pixel.red=(double) ScaleQuantumToChar(GetPixelRed(image,q)); pixel.green=(double) ScaleQuantumToChar(GetPixelGreen(image,q)); pixel.blue=(double) ScaleQuantumToChar(GetPixelBlue(image,q)); for (c=head; c != (Cluster *) NULL; c=c->next) { if ((pixel.red >= (double) (c->red.left-SafeMargin)) && (pixel.red <= (double) (c->red.right+SafeMargin)) && (pixel.green >= (double) (c->green.left-SafeMargin)) && (pixel.green <= (double) (c->green.right+SafeMargin)) && (pixel.blue >= (double) (c->blue.left-SafeMargin)) && (pixel.blue <= (double) (c->blue.right+SafeMargin))) { /* Classify this pixel. */ SetPixelIndex(image,(Quantum) c->id,q); break; } } if (c == (Cluster *) NULL) { double distance_squared, local_minima, numerator, ratio, sum; ssize_t j, k; /* Compute fuzzy membership. */ local_minima=0.0; for (j=0; j < (ssize_t) image->colors; j++) { sum=0.0; p=image->colormap+j; distance_squared= squares[(ssize_t) (pixel.red-ScaleQuantumToChar(p->red))]+ squares[(ssize_t) (pixel.green-ScaleQuantumToChar(p->green))]+ squares[(ssize_t) (pixel.blue-ScaleQuantumToChar(p->blue))]; numerator=distance_squared; for (k=0; k < (ssize_t) image->colors; k++) { p=image->colormap+k; distance_squared= squares[(ssize_t) (pixel.red-ScaleQuantumToChar(p->red))]+ squares[(ssize_t) (pixel.green-ScaleQuantumToChar(p->green))]+ squares[(ssize_t) (pixel.blue-ScaleQuantumToChar(p->blue))]; ratio=numerator/distance_squared; sum+=SegmentPower(ratio); } if ((sum != 0.0) && ((1.0/sum) > local_minima)) { /* Classify this pixel. */ local_minima=1.0/sum; SetPixelIndex(image,(Quantum) j,q); } } } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SegmentImageTag,progress,2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status&=SyncImage(image,exception); /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } squares-=255; free_squares=squares; free_squares=(double *) RelinquishMagickMemory(free_squares); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C r o s s i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCrossings() guarantees that an even number of zero crossings % always lie between two crossings. % % The format of the ConsolidateCrossings method is: % % ConsolidateCrossings(ZeroCrossing *zero_crossing, % const size_t number_crossings) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void ConsolidateCrossings(ZeroCrossing *zero_crossing, const size_t number_crossings) { ssize_t i, j, k, l; ssize_t center, correct, count, left, right; /* Consolidate zero crossings. */ for (i=(ssize_t) number_crossings-1; i >= 0; i--) for (j=0; j <= 255; j++) { if (zero_crossing[i].crossings[j] == 0) continue; /* Find the entry that is closest to j and still preserves the property that there are an even number of crossings between intervals. */ for (k=j-1; k > 0; k--) if (zero_crossing[i+1].crossings[k] != 0) break; left=MagickMax(k,0); center=j; for (k=j+1; k < 255; k++) if (zero_crossing[i+1].crossings[k] != 0) break; right=MagickMin(k,255); /* K is the zero crossing just left of j. */ for (k=j-1; k > 0; k--) if (zero_crossing[i].crossings[k] != 0) break; if (k < 0) k=0; /* Check center for an even number of crossings between k and j. */ correct=(-1); if (zero_crossing[i+1].crossings[j] != 0) { count=0; for (l=k+1; l < center; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (center != k)) correct=center; } /* Check left for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < left; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (left != k)) correct=left; } /* Check right for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < right; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (right != k)) correct=right; } l=(ssize_t) zero_crossing[i].crossings[j]; zero_crossing[i].crossings[j]=0; if (correct != -1) zero_crossing[i].crossings[correct]=(short) l; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineRegion() defines the left and right boundaries of a peak region. % % The format of the DefineRegion method is: % % ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) % % A description of each parameter follows. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o extents: This pointer to an ExtentPacket represent the extends % of a particular peak or valley of a color component. % */ static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) { /* Initialize to default values. */ extents->left=0; extents->center=0.0; extents->right=255; /* Find the left side (maxima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] > 0) break; if (extents->index > 255) return(MagickFalse); /* no left side - no region exists */ extents->left=extents->index; /* Find the right side (minima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] < 0) break; extents->right=extents->index-1; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e r i v a t i v e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DerivativeHistogram() determines the derivative of the histogram using % central differencing. % % The format of the DerivativeHistogram method is: % % DerivativeHistogram(const double *histogram, % double *derivative) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % % o derivative: This array of doubles is initialized by % DerivativeHistogram to the derivative of the histogram using central % differencing. % */ static void DerivativeHistogram(const double *histogram, double *derivative) { ssize_t i, n; /* Compute endpoints using second order polynomial interpolation. */ n=255; derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]); derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]); /* Compute derivative using central differencing. */ for (i=1; i < n; i++) derivative[i]=(histogram[i+1]-histogram[i-1])/2.0; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e D y n a m i c T h r e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDynamicThreshold() returns the dynamic threshold for an image. % % The format of the GetImageDynamicThreshold method is: % % MagickBooleanType GetImageDynamicThreshold(const Image *image, % const double cluster_threshold,const double smooth_threshold, % PixelInfo *pixel,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cluster_threshold: This double represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o pixel: return the dynamic threshold here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image, const double cluster_threshold,const double smooth_threshold, PixelInfo *pixel,ExceptionInfo *exception) { Cluster *background, *cluster, *object, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickBooleanType proceed; double threshold; const Quantum *p; ssize_t i, x; short *extrema[MaxDimension]; ssize_t count, *histogram[MaxDimension], y; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetPixelInfo(image,pixel); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } } /* Initialize histogram. */ InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]); /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireQuantumMemory(1, sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireQuantumMemory(1,sizeof(*cluster)); if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ count=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { double b, g, r; r=(double) ScaleQuantumToChar(GetPixelRed(image,p)); g=(double) ScaleQuantumToChar(GetPixelGreen(image,p)); b=(double) ScaleQuantumToChar(GetPixelBlue(image,p)); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if ((r >= (double) (cluster->red.left-SafeMargin)) && (r <= (double) (cluster->red.right+SafeMargin)) && (g >= (double) (cluster->green.left-SafeMargin)) && (g <= (double) (cluster->green.right+SafeMargin)) && (b >= (double) (cluster->blue.left-SafeMargin)) && (b <= (double) (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=r; cluster->green.center+=g; cluster->blue.center+=b; cluster->count++; break; } p+=GetPixelChannels(image); } proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y, 2*image->rows); if (proceed == MagickFalse) break; } /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } object=head; background=head; if (count > 1) { object=head->next; for (cluster=object; cluster->next != (Cluster *) NULL; ) { if (cluster->count < object->count) object=cluster; cluster=cluster->next; } background=head->next; for (cluster=background; cluster->next != (Cluster *) NULL; ) { if (cluster->count > background->count) background=cluster; cluster=cluster->next; } } if (background != (Cluster *) NULL) { threshold=(background->red.center+object->red.center)/2.0; pixel->red=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->green.center+object->green.center)/2.0; pixel->green=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->blue.center+object->blue.center)/2.0; pixel->blue=(double) ScaleCharToQuantum((unsigned char) (threshold+0.5)); } /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeHistogram() computes the histogram for an image. % % The format of the InitializeHistogram method is: % % InitializeHistogram(const Image *image,ssize_t **histogram) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % */ static void InitializeHistogram(const Image *image,ssize_t **histogram, ExceptionInfo *exception) { const Quantum *p; ssize_t i, x; ssize_t y; /* Initialize histogram. */ for (i=0; i <= 255; i++) { histogram[Red][i]=0; histogram[Green][i]=0; histogram[Blue][i]=0; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(image,p))]++; histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(image,p))]++; histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(image,p))]++; p+=GetPixelChannels(image); } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e I n t e r v a l T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeIntervalTree() initializes an interval tree from the lists of % zero crossings. % % The format of the InitializeIntervalTree method is: % % InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes, % IntervalTree *node) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void InitializeList(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) list[(*number_nodes)++]=node; InitializeList(list,number_nodes,node->sibling); InitializeList(list,number_nodes,node->child); } static void MeanStability(IntervalTree *node) { IntervalTree *child; if (node == (IntervalTree *) NULL) return; node->mean_stability=0.0; child=node->child; if (child != (IntervalTree *) NULL) { ssize_t count; double sum; sum=0.0; count=0; for ( ; child != (IntervalTree *) NULL; child=child->sibling) { sum+=child->stability; count++; } node->mean_stability=sum/(double) count; } MeanStability(node->sibling); MeanStability(node->child); } static void Stability(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) node->stability=0.0; else node->stability=node->tau-(node->child)->tau; Stability(node->sibling); Stability(node->child); } static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing, const size_t number_crossings) { IntervalTree *head, **list, *node, *root; ssize_t i; ssize_t j, k, left, number_nodes; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return((IntervalTree *) NULL); /* The root is the entire histogram. */ root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root)); root->child=(IntervalTree *) NULL; root->sibling=(IntervalTree *) NULL; root->tau=0.0; root->left=0; root->right=255; root->mean_stability=0.0; root->stability=0.0; (void) memset(list,0,TreeLength*sizeof(*list)); for (i=(-1); i < (ssize_t) number_crossings; i++) { /* Initialize list with all nodes with no children. */ number_nodes=0; InitializeList(list,&number_nodes,root); /* Split list. */ for (j=0; j < number_nodes; j++) { head=list[j]; left=head->left; node=head; for (k=head->left+1; k < head->right; k++) { if (zero_crossing[i+1].crossings[k] != 0) { if (node == head) { node->child=(IntervalTree *) AcquireQuantumMemory(1, sizeof(*node->child)); node=node->child; } else { node->sibling=(IntervalTree *) AcquireQuantumMemory(1, sizeof(*node->sibling)); node=node->sibling; } if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=k; left=k; } } if (left != head->left) { node->sibling=(IntervalTree *) AcquireQuantumMemory(1, sizeof(*node->sibling)); node=node->sibling; if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=head->right; } } } /* Determine the stability: difference between a nodes tau and its child. */ Stability(root->child); MeanStability(root->child); list=(IntervalTree **) RelinquishMagickMemory(list); return(root); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m a l T a u % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimalTau() finds the optimal tau for each band of the histogram. % % The format of the OptimalTau method is: % % double OptimalTau(const ssize_t *histogram,const double max_tau, % const double min_tau,const double delta_tau, % const double smooth_threshold,short *extrema) % % A description of each parameter follows. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % */ static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->stability >= node->mean_stability) { list[(*number_nodes)++]=node; ActiveNodes(list,number_nodes,node->sibling); } else { ActiveNodes(list,number_nodes,node->sibling); ActiveNodes(list,number_nodes,node->child); } } static void FreeNodes(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; FreeNodes(node->sibling); FreeNodes(node->child); node=(IntervalTree *) RelinquishMagickMemory(node); } static double OptimalTau(const ssize_t *histogram,const double max_tau, const double min_tau,const double delta_tau,const double smooth_threshold, short *extrema) { double average_tau, *derivative, *second_derivative, tau, value; IntervalTree **list, *node, *root; MagickBooleanType peak; ssize_t i, x; size_t count, number_crossings; ssize_t index, j, k, number_nodes; ZeroCrossing *zero_crossing; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return(0.0); /* Allocate zero crossing list. */ count=(size_t) ((max_tau-min_tau)/delta_tau)+2; zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count, sizeof(*zero_crossing)); if (zero_crossing == (ZeroCrossing *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } for (i=0; i < (ssize_t) count; i++) zero_crossing[i].tau=(-1.0); /* Initialize zero crossing list. */ derivative=(double *) AcquireCriticalMemory(256*sizeof(*derivative)); second_derivative=(double *) AcquireCriticalMemory(256* sizeof(*second_derivative)); i=0; for (tau=max_tau; tau >= min_tau; tau-=delta_tau) { zero_crossing[i].tau=tau; ScaleSpace(histogram,tau,zero_crossing[i].histogram); DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); i++; } /* Add an entry for the original histogram. */ zero_crossing[i].tau=0.0; for (j=0; j <= 255; j++) zero_crossing[i].histogram[j]=(double) histogram[j]; DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); number_crossings=(size_t) i; derivative=(double *) RelinquishMagickMemory(derivative); second_derivative=(double *) RelinquishMagickMemory(second_derivative); /* Ensure the scale-space fingerprints form lines in scale-space, not loops. */ ConsolidateCrossings(zero_crossing,number_crossings); /* Force endpoints to be included in the interval. */ for (i=0; i <= (ssize_t) number_crossings; i++) { for (j=0; j < 255; j++) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]); for (j=255; j > 0; j--) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]); } /* Initialize interval tree. */ root=InitializeIntervalTree(zero_crossing,number_crossings); if (root == (IntervalTree *) NULL) { zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } /* Find active nodes: Stability is greater (or equal) to the mean stability of its children. */ number_nodes=0; ActiveNodes(list,&number_nodes,root->child); /* Initialize extrema. */ for (i=0; i <= 255; i++) extrema[i]=0; for (i=0; i < number_nodes; i++) { /* Find this tau in zero crossings list. */ k=0; node=list[i]; for (j=0; j <= (ssize_t) number_crossings; j++) if (zero_crossing[j].tau == node->tau) k=j; /* Find the value of the peak. */ peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue : MagickFalse; index=node->left; value=zero_crossing[k].histogram[index]; for (x=node->left; x <= node->right; x++) { if (peak != MagickFalse) { if (zero_crossing[k].histogram[x] > value) { value=zero_crossing[k].histogram[x]; index=x; } } else if (zero_crossing[k].histogram[x] < value) { value=zero_crossing[k].histogram[x]; index=x; } } for (x=node->left; x <= node->right; x++) { if (index == 0) index=256; if (peak != MagickFalse) extrema[x]=(short) index; else extrema[x]=(short) (-index); } } /* Determine the average tau. */ average_tau=0.0; for (i=0; i < number_nodes; i++) average_tau+=list[i]->tau; average_tau*=PerceptibleReciprocal((double) number_nodes); /* Relinquish resources. */ FreeNodes(root); zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(average_tau); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S c a l e S p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleSpace() performs a scale-space filter on the 1D histogram. % % The format of the ScaleSpace method is: % % ScaleSpace(const ssize_t *histogram,const double tau, % double *scale_histogram) % % A description of each parameter follows. % % o histogram: Specifies an array of doubles representing the number % of pixels for each intensity of a particular color component. % */ static void ScaleSpace(const ssize_t *histogram,const double tau, double *scale_histogram) { double alpha, beta, *gamma, sum; ssize_t u, x; gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma)); if (gamma == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAllocateGammaMap"); alpha=PerceptibleReciprocal(tau*sqrt(2.0*MagickPI)); beta=(-1.0*PerceptibleReciprocal(2.0*tau*tau)); for (x=0; x <= 255; x++) gamma[x]=0.0; for (x=0; x <= 255; x++) { gamma[x]=exp((double) beta*x*x); if (gamma[x] < MagickEpsilon) break; } for (x=0; x <= 255; x++) { sum=0.0; for (u=0; u <= 255; u++) sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)]; scale_histogram[x]=alpha*sum; } gamma=(double *) RelinquishMagickMemory(gamma); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e g m e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SegmentImage() segment an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % C-means technique. % % The format of the SegmentImage method is: % % MagickBooleanType SegmentImage(Image *image, % const ColorspaceType colorspace,const MagickBooleanType verbose, % const double cluster_threshold,const double smooth_threshold, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o colorspace: Indicate the colorspace. % % o verbose: Set to MagickTrue to print detailed information about the % identified classes. % % o cluster_threshold: This represents the minimum number of pixels % contained in a hexahedra before it can be considered valid (expressed % as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SegmentImage(Image *image, const ColorspaceType colorspace,const MagickBooleanType verbose, const double cluster_threshold,const double smooth_threshold, ExceptionInfo *exception) { ColorspaceType previous_colorspace; MagickBooleanType status; ssize_t i; short *extrema[MaxDimension]; ssize_t *histogram[MaxDimension]; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename) } } /* Initialize histogram. */ previous_colorspace=image->colorspace; (void) TransformImageColorspace(image,colorspace,exception); InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau,smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]); /* Classify using the fuzzy c-Means technique. */ status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose, exception); (void) TransformImageColorspace(image,previous_colorspace,exception); /* Relinquish resources. */ for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Z e r o C r o s s H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroCrossHistogram() find the zero crossings in a histogram and marks % directions as: 1 is negative to positive; 0 is zero crossing; and -1 % is positive to negative. % % The format of the ZeroCrossHistogram method is: % % ZeroCrossHistogram(double *second_derivative, % const double smooth_threshold,short *crossings) % % A description of each parameter follows. % % o second_derivative: Specifies an array of doubles representing the % second derivative of the histogram of a particular color component. % % o crossings: This array of integers is initialized with % -1, 0, or 1 representing the slope of the first derivative of the % of a particular color component. % */ static void ZeroCrossHistogram(double *second_derivative, const double smooth_threshold,short *crossings) { ssize_t i; ssize_t parity; /* Merge low numbers to zero to help prevent noise. */ for (i=0; i <= 255; i++) if ((second_derivative[i] < smooth_threshold) && (second_derivative[i] >= -smooth_threshold)) second_derivative[i]=0.0; /* Mark zero crossings. */ parity=0; for (i=0; i <= 255; i++) { crossings[i]=0; if (second_derivative[i] < 0.0) { if (parity > 0) crossings[i]=(-1); parity=1; } else if (second_derivative[i] > 0.0) { if (parity < 0) crossings[i]=1; parity=(-1); } } }
ZQ_FaceDatabaseCompact.h
#ifndef _ZQ_FACE_DATABASE_COMPACT_H_ #define _ZQ_FACE_DATABASE_COMPACT_H_ #pragma once #include <malloc.h> #include <stdio.h> #include <vector> #include <omp.h> #include "ZQ_FaceRecognizerSphereFace.h" #include "ZQ_MathBase.h" #include "ZQ_MergeSort.h" namespace ZQ { class ZQ_FaceDatabaseCompact { enum CONST_VAL { FEAT_ALIGNED_SIZE = 32 }; public: ZQ_FaceDatabaseCompact() { dim = 0; person_num = 0; person_face_num = 0; total_face_num = 0; person_face_offset = 0; all_face_feats = 0; } ~ZQ_FaceDatabaseCompact() {} bool LoadFromFile(const char* feats_file, const char* names_file) { _clear(); if (!_load_feats(feats_file)) { _clear(); return false; } if (!_load_names(names_file)) { _clear(); return false; } if (person_num != names.size()) { _clear(); return false; } return true; } bool Search(int feat_dim, int feat_num, const float* feat, std::vector<int>& out_ids, std::vector<float>& out_scores, std::vector<std::string>& out_names, int max_num, int max_thread_num) const { return _find_the_best_matches(feat_dim, feat_num, feat, out_ids, out_scores, out_names, max_num, max_thread_num); } bool ExportSimilarityForAllPairs(const std::string& out_score_file, const std::string& out_flag_file, __int64& all_pair_num, __int64& same_pair_num, __int64& notsame_pair_num, int max_thread_num, bool quantization) const { return _export_similarity_for_all_pairs(out_score_file,out_flag_file, all_pair_num, same_pair_num, notsame_pair_num, max_thread_num, quantization); } bool DetectRepeatPerson(const std::string& out_file, int max_thread_num, float similarity_thresh = 0.5, bool only_pivot = true) const { return _detect_repeat_person(out_file, max_thread_num, similarity_thresh, only_pivot); } private: int dim; int person_num; int* person_face_num; __int64 total_face_num; __int64* person_face_offset; float* all_face_feats; std::vector<std::string> names; private: void _clear() { dim = 0; person_num = 0; total_face_num = 0; if (person_face_num) { free(person_face_num); person_face_num = 0; } if (person_face_offset) { free(person_face_offset); person_face_offset = 0; } if (all_face_feats) { _aligned_free(all_face_feats); all_face_feats = 0; } names.clear(); } bool _load_feats(const char* file) { FILE* in = 0; if (0 != fopen_s(&in, file, "rb")) { return false; } if (1 != fread(&dim, sizeof(int), 1, in) || dim <= 0) { fclose(in); return false; } if (1 != fread(&person_num, sizeof(int), 1, in) || person_num <= 0) { fclose(in); return false; } person_face_num = (int*)malloc(sizeof(int)*person_num); person_face_offset = (__int64*)malloc(sizeof(__int64)*person_num); if (person_face_num == 0 || person_face_offset == 0) { fclose(in); return false; } if (person_num != fread(person_face_num, sizeof(int), person_num, in)) { fclose(in); return false; } total_face_num = 0; for (int i = 0; i < person_num; i++) { if (person_face_num[i] <= 0) { fclose(in); return false; } person_face_offset[i] = total_face_num; total_face_num += person_face_num[i]; } all_face_feats = (float*)_aligned_malloc(sizeof(float)*total_face_num*dim, FEAT_ALIGNED_SIZE); if (all_face_feats == 0) { fclose(in); return false; } if (total_face_num*dim != fread(all_face_feats, sizeof(float), total_face_num*dim, in)) { fclose(in); return false; } fclose(in); return true; } bool _load_names(const char* file) { FILE* in = 0; if (0 != fopen_s(&in, file, "r")) return false; char line[200] = { 0 }; while (true) { line[0] = '\0'; fgets(line, 199, in); if (line[0] == '\0') break; int len = strlen(line); if (line[len - 1] == '\n') line[--len] = '\0'; names.push_back(std::string(line)); } fclose(in); return true; } bool _find_the_best_matches(int feat_dim, int feat_num, const float* feat, std::vector<int>& out_ids, std::vector<float>& out_scores, std::vector<std::string>& out_names, int max_num, int max_thread_num) const { if (person_num <= 0 || feat_dim != dim || feat_num <= 0) return false; int widthStep = (sizeof(float)*dim + FEAT_ALIGNED_SIZE-1) / FEAT_ALIGNED_SIZE * FEAT_ALIGNED_SIZE; float* feat_aligned = (float*)_aligned_malloc(widthStep*feat_num, FEAT_ALIGNED_SIZE); if (feat_aligned == 0) return false; for(int i = 0;i < feat_num;i++) memcpy(((char*)feat_aligned)+widthStep*i, feat+feat_dim*i, sizeof(float)*dim); float* scores = (float*)malloc(sizeof(float)*total_face_num); if (scores == 0) { _aligned_free(feat_aligned); return false; } for (int i = 0; i < total_face_num; i++) scores[i] = -FLT_MAX; int num_procs = omp_get_num_procs(); int real_threads = __max(1, __min(max_thread_num, num_procs - 1)); if (real_threads == 1) { for (int j = 0; j < feat_num; j++) { float* tmp_feat = (float*)(((char*)feat_aligned) + widthStep*j); int chunk_size = (total_face_num + real_threads - 1) / real_threads; if (dim == 128) { for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i],ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim128(tmp_feat, all_face_feats + i*dim)); } } else if (dim == 256) { for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim256(tmp_feat, all_face_feats + i*dim)); } } else if (dim == 512) { for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim512(tmp_feat, all_face_feats + i*dim)); } } else { for (long long i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_MathBase::DotProduct(dim, tmp_feat, all_face_feats + i*dim)); } } } } else { for (int j = 0; j < feat_num; j++) { float* tmp_feat = (float*)(((char*)feat_aligned) + widthStep*j); int chunk_size = (total_face_num + real_threads - 1) / real_threads; if (dim == 128) { #pragma omp parallel for schedule(static, chunk_size) num_threads(real_threads) for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim128(tmp_feat, all_face_feats + i*dim)); } } else if (dim == 256) { #pragma omp parallel for schedule(static, chunk_size) num_threads(real_threads) for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim256(tmp_feat, all_face_feats + i*dim)); } } else if (dim == 512) { #pragma omp parallel for schedule(static, chunk_size) num_threads(real_threads) for (int i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim512(tmp_feat, all_face_feats + i*dim)); } } else { #pragma omp parallel for schedule(static, chunk_size) num_threads(real_threads) for (long long i = 0; i < total_face_num; i++) { scores[i] = __max(scores[i], ZQ_MathBase::DotProduct(dim, tmp_feat, all_face_feats + i*dim)); } } } } float* max_scores = (float*)malloc(sizeof(float)*person_num); if (max_scores == 0) { _aligned_free(feat_aligned); free(scores); return false; } if (real_threads == 1) { for (int i = 0; i < person_num; i++) { float tmp = -FLT_MAX; for (long long j = person_face_offset[i]; j < person_face_offset[i]+person_face_num[i]; j++) { tmp = __max(tmp, scores[j]); } max_scores[i] = tmp; } } else { int chunk_size = (person_num + real_threads - 1) / real_threads; #pragma omp parallel for schedule(static, chunk_size) num_threads(real_threads) for (int i = 0; i < person_num; i++) { float tmp = -FLT_MAX; for (long long j = person_face_offset[i]; j < person_face_offset[i] + person_face_num[i]; j++) { tmp = __max(tmp, scores[j]); } max_scores[i] = tmp; } } _aligned_free(feat_aligned); free(scores); int* ids = (int*)malloc(sizeof(int)*person_num); if (ids == 0) { free(max_scores); return false; } for (int i = 0; i < person_num; i++) { ids[i] = i; } out_ids.clear(); out_scores.clear(); out_names.clear(); for (int i = 0; i < __min(max_num, person_num); i++) { float cur_max_score = max_scores[i]; int max_id = i; for (int j = i + 1; j < person_num; j++) { if (cur_max_score < max_scores[j]) { max_id = j; cur_max_score = max_scores[j]; } } int tmp_id = ids[i]; ids[i] = ids[max_id]; ids[max_id] = tmp_id; float tmp_score = max_scores[i]; max_scores[i] = max_scores[max_id]; max_scores[max_id] = tmp_score; out_ids.push_back(ids[i]); out_scores.push_back(max_scores[i]); out_names.push_back(names[ids[i]]); } free(max_scores); free(ids); return true; } //must be aligned static float _compute_similarity(int dim, const float* v1, const float* v2) { if (dim == 128) return ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim128(v1, v2); else if (dim == 256) return ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim256(v1, v2); else if (dim == 512) return ZQ_FaceRecognizerSphereFace::_cal_similarity_avx_dim512(v1, v2); else return ZQ_MathBase::DotProduct(dim, v1, v2); } bool _export_similarity_for_all_pairs(const std::string& out_score_file, const std::string& out_flag_file, __int64& all_pair_num, __int64& same_pair_num, __int64& notsame_pair_num, int max_thread_num, bool quantization) const { FILE* out1 = 0; if (0 != fopen_s(&out1, out_score_file.c_str(), "wb")) { printf("failed to create file %s\n", out_score_file.c_str()); return false; } FILE* out2 = 0; if (0 != fopen_s(&out2, out_flag_file.c_str(), "wb")) { printf("failed to create file %s\n", out_flag_file.c_str()); fclose(out1); return false; } all_pair_num = total_face_num *(total_face_num - 1) / 2; same_pair_num = 0; notsame_pair_num = 0; //fprintf(out, "%lld\n", total_pair_num); int real_thread_num = __max(1, __min(max_thread_num, omp_get_num_procs() - 1)); if (real_thread_num == 1) { for (int pp = 0; pp < person_num; pp++) { __int64 cur_face_offset = person_face_offset[pp]; __int64 cur_face_num = person_face_num[pp]; __int64 max_pair_num = (total_face_num - cur_face_offset - 1); std::vector<float> scores(max_pair_num); std::vector<char> flags(max_pair_num); for (__int64 i = 0; i < cur_face_num; i++) { float* cur_i_feat = all_face_feats + (cur_face_offset + i)*dim; float* cur_j_feat; int idx = 0; for (__int64 j = i + 1; j < cur_face_num; j++) { cur_j_feat = all_face_feats + (cur_face_offset + j)*dim; scores[idx] = _compute_similarity(dim, cur_i_feat, cur_j_feat); flags[idx] = 1; same_pair_num++; idx++; } if (pp + 1 < person_num) { for (__int64 j = person_face_offset[pp + 1]; j < total_face_num; j++) { cur_j_feat = all_face_feats + j*dim; scores[idx] = _compute_similarity(dim, cur_i_feat, cur_j_feat); flags[idx] = 0; notsame_pair_num++; idx++; } } if (idx > 0) { if (quantization) { std::vector<short> short_scores(idx); for (int j = 0; j < idx; j++) short_scores[j] = __min(SHRT_MAX, __max(-SHRT_MAX, scores[j] * SHRT_MAX)); fwrite(&short_scores[0], sizeof(short), idx, out1); } else { fwrite(&scores[0], sizeof(float), idx, out1); } fwrite(&flags[0], 1, idx, out2); } } printf("%d/%d handled\n", pp + 1, person_num); } } else { int chunk_size = 100; int handled[1] = { 0 }; __int64 tmp_same_pair_num[1] = { 0 }; printf("real_thread_num = %d\n", real_thread_num); #pragma omp parallel for schedule(dynamic,chunk_size) num_threads(real_thread_num) shared(handled) for (int pp = 0; pp < person_num; pp++) { __int64 cur_face_offset = person_face_offset[pp]; __int64 cur_face_num = person_face_num[pp]; __int64 max_pair_num = (total_face_num - cur_face_offset-1); std::vector<float> scores(max_pair_num); std::vector<char> flags(max_pair_num); for (__int64 i = 0; i < cur_face_num; i++) { float* cur_i_feat = all_face_feats + (cur_face_offset + i)*dim; float* cur_j_feat; int idx = 0; for (__int64 j = i+1; j < cur_face_num; j++) { cur_j_feat = all_face_feats + (cur_face_offset + j)*dim; scores[idx] = _compute_similarity(dim, cur_i_feat, cur_j_feat); flags[idx] = 1; idx++; } if (pp + 1 < person_num) { for (__int64 j = person_face_offset[pp + 1]; j < total_face_num; j++) { cur_j_feat = all_face_feats + j*dim; scores[idx] = _compute_similarity(dim, cur_i_feat, cur_j_feat); flags[idx] = 0; idx++; } } #pragma omp critical { if (idx > 0) { for (int kk = 0; kk < idx; kk++) { (*tmp_same_pair_num) += flags[kk]; } if (quantization) { std::vector<short> short_scores(idx); for (int j = 0; j < idx; j++) short_scores[j] = __min(SHRT_MAX, __max(-SHRT_MAX, scores[j] * SHRT_MAX)); fwrite(&short_scores[0], sizeof(short), idx, out1); } else { fwrite(&scores[0], sizeof(float), idx, out1); } fwrite(&flags[0], 1, idx, out2); } } } #pragma omp critical { (*handled) ++; printf("%d/%d\n", *handled, person_num); } } same_pair_num = tmp_same_pair_num[0]; notsame_pair_num = all_pair_num - same_pair_num; } fclose(out1); fclose(out2); return true; } bool _detect_repeat_person(const std::string& out_file, int max_thread_num, float similarity_thresh, bool only_pivot) const { std::vector<std::pair<int, int>> repeat_pairs; std::vector<float> scores; if (!_detect_repeat_person(repeat_pairs, scores, max_thread_num, similarity_thresh, only_pivot)) { return false; } __int64 num = scores.size(); printf("num = %lld\n", num); if (num > 0) { ZQ_MergeSort::MergeSortWithData(&scores[0], &repeat_pairs[0], sizeof(std::pair<int, int>), num, false); } FILE* out = 0; if (0 != fopen_s(&out, out_file.c_str(), "w")) { return false; } for (__int64 i = 0; i < num; i++) { fprintf(out, "%.3f %s %s\n", scores[i], names[repeat_pairs[i].first].c_str(), names[repeat_pairs[i].second].c_str()); } fclose(out); return true; } bool _detect_repeat_person(std::vector<std::pair<int, int>>& repeat_pairs, std::vector<float>& repeat_scores, int max_thread_num, float similarity_thresh, bool only_pivot) const { repeat_pairs.clear(); repeat_scores.clear(); if (only_pivot) { std::vector<int> pivot_ids(person_num); if (max_thread_num <= 1) { for (int p = 0; p < person_num; p++) { __int64 cur_offset = person_face_offset[p]; __int64 cur_num = person_face_num[p]; std::vector<float> scores(cur_num*cur_num); int idx = 0; for (__int64 i = 0; i < cur_num; i++) { float* cur_i_feat = all_face_feats + (cur_offset + i)*dim; float* cur_j_feat; scores[i*cur_num + i] = 1; for (__int64 j = i + 1; j < cur_num; j++) { cur_j_feat = all_face_feats + (cur_offset + j)*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); scores[i*cur_num + j] = tmp_score; scores[j*cur_num + i] = tmp_score; } } int pivot_id = -1; float sum_score = -FLT_MAX; for (int i = 0; i < cur_num; i++) { float tmp_sum = 0; for (int j = 0; j < cur_num; j++) tmp_sum += scores[i*cur_num + j]; if (sum_score < tmp_sum) { pivot_id = i; sum_score = tmp_sum; } } pivot_ids[p] = pivot_id; } // for (int i = 0; i < person_num; i++) { for (int j = i + 1; j < person_num; j++) { const float* cur_i_feat = all_face_feats + (person_face_offset[i] + pivot_ids[i])*dim; const float* cur_j_feat = all_face_feats + (person_face_offset[j] + pivot_ids[j])*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); if (tmp_score >= similarity_thresh) { repeat_pairs.push_back(std::make_pair(i, j)); repeat_scores.push_back(tmp_score); } } } } else { int chunk_size = (person_num + max_thread_num - 1) / max_thread_num; #pragma omp parallel for schedule(static,chunk_size) num_threads(max_thread_num) for (int p = 0; p < person_num; p++) { __int64 cur_offset = person_face_offset[p]; __int64 cur_num = person_face_num[p]; std::vector<float> scores(cur_num*cur_num); int idx = 0; for (__int64 i = 0; i < cur_num; i++) { float* cur_i_feat = all_face_feats + (cur_offset + i)*dim; float* cur_j_feat; scores[i*cur_num + i] = 1; for (__int64 j = i + 1; j < cur_num; j++) { cur_j_feat = all_face_feats + (cur_offset + j)*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); scores[i*cur_num + j] = tmp_score; scores[j*cur_num + i] = tmp_score; } } int pivot_id = -1; float sum_score = -FLT_MAX; for (int i = 0; i < cur_num; i++) { float tmp_sum = 0; for (int j = 0; j < cur_num; j++) tmp_sum += scores[i*cur_num + j]; if (sum_score < tmp_sum) { pivot_id = i; sum_score = tmp_sum; } } pivot_ids[p] = pivot_id; } #pragma omp parallel for schedule(static,chunk_size) num_threads(max_thread_num) for (int i = 0; i < person_num; i++) { for (int j = i + 1; j < person_num; j++) { const float* cur_i_feat = all_face_feats + (person_face_offset[i] + pivot_ids[i])*dim; const float* cur_j_feat = all_face_feats + (person_face_offset[j] + pivot_ids[j])*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); if (tmp_score >= similarity_thresh) { #pragma omp critical { repeat_pairs.push_back(std::make_pair(i, j)); repeat_scores.push_back(tmp_score); } } } } } } else { if (max_thread_num <= 1) { int handled[1] = { 0 }; for (int i = 0; i < person_num; i++) { for (int j = i + 1; j < person_num; j++) { float max_score = -FLT_MAX; for (int s = 0; s < person_face_num[i]; s++) { for (int t = 0; t < person_face_num[j]; t++) { const float* cur_i_feat = all_face_feats + (person_face_offset[i] + s)*dim; const float* cur_j_feat = all_face_feats + (person_face_offset[j] + t)*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); max_score = __max(max_score, tmp_score); } } if (max_score >= similarity_thresh) { repeat_pairs.push_back(std::make_pair(i, j)); repeat_scores.push_back(max_score); } } handled[0]++; if (handled[0] % 10 == 0) { printf("%d/%d handled\n", handled[0], person_num); } } } else { int handled[1] = { 0 }; int chunk_size = (person_num + max_thread_num - 1) / max_thread_num; #pragma omp parallel for schedule(static,chunk_size) num_threads(max_thread_num) for (int i = 0; i < person_num; i++) { for (int j = i + 1; j < person_num; j++) { float max_score = -FLT_MAX; for (int s = 0; s < person_face_num[i]; s++) { for (int t = 0; t < person_face_num[j]; t++) { const float* cur_i_feat = all_face_feats + (person_face_offset[i] + s)*dim; const float* cur_j_feat = all_face_feats + (person_face_offset[j] + t)*dim; float tmp_score = _compute_similarity(dim, cur_i_feat, cur_j_feat); max_score = __max(max_score, tmp_score); } } if (max_score >= similarity_thresh) { #pragma omp critical { repeat_pairs.push_back(std::make_pair(i, j)); repeat_scores.push_back(max_score); } } } #pragma omp critical { handled[0] ++; if (handled[0] % 10 == 0) { printf("%d/%d handled\n", handled[0], person_num); } } } } } return true; } }; } #endif
explicit_solver_strategy.h
// // Authors: // Miguel Angel Celigueta maceli@cimne.upc.edu // Miquel Santasusana msantasusana@cimne.upc.edu // #if !defined(KRATOS_EXPLICIT_SOLVER_STRATEGY) #define KRATOS_EXPLICIT_SOLVER_STRATEGY // Project includes #include "utilities/timer.h" #include "custom_elements/Particle_Contact_Element.h" #include "includes/variables.h" #include "includes/deprecated_variables.h" /* System includes */ #include <limits> #include <iostream> #include <iomanip> #include <time.h> /* External includes */ #ifdef _OPENMP #include <omp.h> #endif #define CUSTOMTIMER 0 // ACTIVATES AND DISABLES ::TIMER::::: #include "includes/define.h" #include "utilities/openmp_utils.h" #include "includes/model_part.h" #include "solving_strategies/strategies/solving_strategy.h" #include "solving_strategies/schemes/scheme.h" #include "custom_strategies/schemes/dem_integration_scheme.h" #include "custom_utilities/create_and_destroy.h" #include "custom_utilities/dem_fem_utilities.h" #include "custom_utilities/GeometryFunctions.h" #include "custom_utilities/inlet.h" #include "custom_elements/cluster3D.h" #include "custom_elements/rigid_body_element.h" ////Cfeng #include "custom_utilities/dem_fem_search.h" #include "custom_utilities/discrete_particle_configure.h" #include "custom_utilities/rigid_face_geometrical_object_configure.h" #ifdef USING_CGAL #include <CGAL/spatial_sort.h> #endif /* Timer defines */ #ifdef CUSTOMTIMER #define KRATOS_TIMER_START(t) Timer::Start(t); #define KRATOS_TIMER_STOP(t) Timer::Stop(t); #else #define KRATOS_TIMER_START(t) #define KRATOS_TIMER_STOP(t) #endif namespace Kratos { class ExplicitSolverSettings { public: KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverSettings); ExplicitSolverSettings() { } ~ExplicitSolverSettings() { } ModelPart* r_model_part; ModelPart* contact_model_part; ModelPart* fem_model_part; ModelPart* cluster_model_part; ModelPart* inlet_model_part; }; class KRATOS_API(DEM_APPLICATION) ExplicitSolverStrategy { public: typedef ModelPart::NodesContainerType NodesArrayType; typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ElementsArrayType::iterator ElementsIterator; typedef ModelPart::ConditionsContainerType ConditionsArrayType; typedef ModelPart::NodesContainerType::ContainerType NodesContainerType; typedef ModelPart::ElementsContainerType::ContainerType ElementsContainerType; typedef ModelPart::ConditionsContainerType::ContainerType ConditionsContainerType; typedef SpatialSearch::ResultElementsContainerType ResultElementsContainerType; typedef SpatialSearch::VectorResultElementsContainerType VectorResultElementsContainerType; typedef SpatialSearch::RadiusArrayType RadiusArrayType; typedef SpatialSearch::DistanceType DistanceType; typedef SpatialSearch::VectorDistanceType VectorDistanceType; typedef SpatialSearch::ResultConditionsContainerType ResultConditionsContainerType; typedef SpatialSearch::VectorResultConditionsContainerType VectorResultConditionsContainerType; typedef PointerVectorSet<Properties, IndexedObject> PropertiesContainerType; typedef PropertiesContainerType::iterator PropertiesIterator; typedef DiscreteParticleConfigure<3> ElementConfigureType; typedef RigidFaceGeometricalObjectConfigure<3> RigidFaceGeometricalConfigureType; typedef Kratos::VariableComponent<Kratos::VectorComponentAdaptor<Kratos::array_1d<double, 3ul> > > ComponentOf3ComponentsVariableType; /// Pointer definition of ExplicitSolverStrategy KRATOS_CLASS_POINTER_DEFINITION(ExplicitSolverStrategy); ExplicitSolverStrategy() { } ExplicitSolverStrategy(ExplicitSolverSettings& settings, const double max_delta_time, const int n_step_search, const double safety_factor, const int delta_option, ParticleCreatorDestructor::Pointer p_creator_destructor, DEM_FEM_Search::Pointer p_dem_fem_search, SpatialSearch::Pointer pSpSearch, Parameters strategy_parameters) { mParameters = strategy_parameters; mDeltaOption = delta_option; mpParticleCreatorDestructor = p_creator_destructor; mpDemFemSearch = p_dem_fem_search; mpSpSearch = pSpSearch; if(mParameters["do_search_neighbours"].GetBool()) mDoSearchNeighbourElements = true; else mDoSearchNeighbourElements = false; p_creator_destructor->SetDoSearchNeighbourElements(mDoSearchNeighbourElements); mMaxTimeStep = max_delta_time; mNStepSearch = n_step_search; mSafetyFactor = safety_factor; mpDem_model_part = &(*(settings.r_model_part)); if (mpDem_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.r_model_part in ExplicitSolverStrategy constructor", "") mpContact_model_part = &(*(settings.contact_model_part)); if (mpContact_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.contact_model_part in ExplicitSolverStrategy constructor", "") mpFem_model_part = &(*(settings.fem_model_part)); if (mpFem_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.fem_model_part in ExplicitSolverStrategy constructor", "") mpCluster_model_part = &(*(settings.cluster_model_part)); if (mpCluster_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.cluster_model_part in ExplicitSolverStrategy constructor", "") mpInlet_model_part = &(*(settings.inlet_model_part)); if (mpInlet_model_part == NULL) KRATOS_THROW_ERROR(std::runtime_error, "Undefined settings.inlet_model_part in ExplicitSolverStrategy constructor", "") if(mParameters["RemoveBallsInitiallyTouchingWalls"].GetBool()) mRemoveBallsInitiallyTouchingWallsOption = true; else mRemoveBallsInitiallyTouchingWallsOption = false; } /// Destructor. virtual ~ExplicitSolverStrategy() { //Timer::SetOuputFile("TimesPartialRelease"); //Timer::PrintTimingInformation(); } struct LessX { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[0] < q->GetGeometry()[0].Coordinates()[0];} }; struct LessY { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[1] < q->GetGeometry()[0].Coordinates()[1];} }; struct LessZ { bool operator()(const SphericParticle* p, const SphericParticle* q) const {return p->GetGeometry()[0].Coordinates()[2] < q->GetGeometry()[0].Coordinates()[2];} }; struct SpatialSortingTraits { typedef SphericParticle* Point_2; typedef LessX Less_x_2; typedef LessY Less_y_2; typedef LessZ Less_z_2; Less_x_2 less_x_2_object() const {return Less_x_2();} Less_y_2 less_y_2_object() const {return Less_y_2();} Less_z_2 less_z_2_object() const { return Less_z_2();} }; #ifdef USING_CGAL void ReorderParticles() { SpatialSortingTraits sst; CGAL::spatial_sort(mListOfSphericParticles.begin(), mListOfSphericParticles.end(), sst); } #endif template <class T> void RebuildListOfSphericParticles(ElementsArrayType& pElements, std::vector<T*>& rCustomListOfParticles){ KRATOS_TRY rCustomListOfParticles.resize(pElements.size()); #pragma omp parallel for for (int k = 0; k < (int)pElements.size(); k++){ ElementsArrayType::iterator particle_pointer_it = pElements.ptr_begin() + k; T* spheric_particle = dynamic_cast<T*>(&(*particle_pointer_it)); rCustomListOfParticles[k] = spheric_particle; } return; KRATOS_CATCH("") } void RebuildListOfDiscontinuumSphericParticles() { RebuildListOfSphericParticles<SphericParticle>(GetModelPart().GetCommunicator().LocalMesh().Elements(), mListOfSphericParticles); } void RebuildPropertiesProxyPointers(std::vector<SphericParticle*>& rCustomListOfSphericParticles); void SendProcessInfoToClustersModelPart(); void UpdateMaxIdOfCreatorDestructor(); void RepairPointersToNormalProperties(std::vector<SphericParticle*>& rCustomListOfSphericParticles); virtual void Initialize(); virtual void AttachSpheresToStickyWalls(); virtual void DisplayThreadInfo(); virtual void CalculateMaxTimeStep(); double CalculateMaxInletTimeStep(); virtual void InitializeClusters(); virtual void GetClustersForce(); virtual void GetRigidBodyElementsForce(); virtual double Solve(); void SearchDEMOperations(ModelPart& r_model_part, bool has_mpi = true); void SearchFEMOperations(ModelPart& r_model_part, bool has_mpi = true) ; virtual void ForceOperations(ModelPart& r_model_part); void InitialTimeStepCalculation(); //TODO: remove this one void GetForce(); void FastGetForce(); virtual void PerformTimeIntegrationOfMotion(int StepFlag = 0); void InitializeSolutionStep(); virtual void BoundingBoxUtility(bool is_time_to_mark_and_remove = true); virtual void FinalizeSolutionStep(); void InitializeElements(); void InitializeDEMElements(); void InitializeFEMElements(); //void InitializeRigidBodyElements(); void InitializeFEMWallsAsRigidBodyElements(ModelPart::SubModelPartsContainerType::iterator& sub_model_part); void MarkToDeleteAllSpheresInitiallyIndentedWithFEM(ModelPart& rSpheresModelPart); void ComputeNodalArea(); void ComputeNormalPressureVectorField(); virtual void CalculateConditionsRHSAndAdd(); void ClearFEMForces(); void CalculateNodalPressuresAndStressesOnWalls(); void SetFlagAndVariableToNodes(const Kratos::Flags& r_flag_name, ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void SetVariableToNodes(ComponentOf3ComponentsVariableType& r_variable_to_set, const double value, NodesArrayType& r_nodes_array); void ResetPrescribedMotionFlagsRespectingImposedDofs(); void ApplyPrescribedBoundaryConditions(); void ApplyInitialConditions(); void SetSearchRadiiOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); void SetNormalRadiiOnAllParticles(ModelPart& r_model_part); void SetSearchRadiiWithFemOnAllParticles(ModelPart& r_model_part, const double added_search_distance = 0.0, const double amplification = 1.0); virtual void SearchNeighbours(); virtual void ComputeNewNeighboursHistoricalData(); virtual void CreateContactElements(); void InitializeContactElements(); // void ContactInitializeSolutionStep(); void PrepareContactElementsForPrinting(); virtual void ComputeNewRigidFaceNeighboursHistoricalData(); virtual void SearchRigidFaceNeighbours(); void CheckHierarchyWithCurrentNeighbours(); /* This should work only with one iteration, but it with mpi does not */ void CalculateInitialMaxIndentations(ProcessInfo& r_process_info); void PrepareContactModelPart(ModelPart& r_model_part, ModelPart& mcontacts_model_part); void PrepareElementsForPrinting(); void SynchronizeHistoricalVariables(ModelPart& r_model_part); void SynchronizeRHS(ModelPart& r_model_part); void CleanEnergies(); ModelPart& GetModelPart() { return (*mpDem_model_part);} ModelPart& GetFemModelPart() { return (*mpFem_model_part);} ModelPart& GetContactModelPart() { return (*mpContact_model_part);} ModelPart& GetClusterModelPart() { return (*mpCluster_model_part);} ModelPart& GetInletModelPart() { return (*mpInlet_model_part);} ModelPart& GetRigidBodyModelPart() { return (*mpRigidBody_model_part);} VectorResultElementsContainerType& GetResults() { return (mResults);} VectorDistanceType& GetResultsDistances() { return (mResultsDistances);} RadiusArrayType& GetArrayOfAmplifiedRadii() { return (mArrayOfAmplifiedRadii);} int& GetNStepSearch() { return (mNStepSearch);} int& GetSearchControl() { return mSearchControl;} int& GetNumberOfThreads() { return (mNumberOfThreads);} double& GetMaxTimeStep() { return (mMaxTimeStep);} double& GetSafetyFactor() { return (mSafetyFactor);} int& GetDeltaOption() { return (mDeltaOption);} std::vector<unsigned int>& GetElementPartition() { return (mElementPartition);} ParticleCreatorDestructor::Pointer& GetParticleCreatorDestructor() { return (mpParticleCreatorDestructor);} SpatialSearch::Pointer& GetSpSearch() { return (mpSpSearch);} VectorResultConditionsContainerType& GetRigidFaceResults() { return (mRigidFaceResults);} VectorDistanceType& GetRigidFaceResultsDistances() { return (mRigidFaceResultsDistances);} std::vector<unsigned int>& GetConditionPartition() { return (mConditionPartition);} DEM_FEM_Search::Pointer& GetDemFemSearch() { return (mpDemFemSearch);} virtual ElementsArrayType& GetElements(ModelPart& r_model_part) { return r_model_part.GetCommunicator().LocalMesh().Elements();} virtual ElementsArrayType& GetAllElements(ModelPart& r_model_part) { return r_model_part.Elements(); } protected: Parameters mParameters; bool mRemoveBallsInitiallyTouchingWallsOption; VectorResultElementsContainerType mResults; VectorDistanceType mResultsDistances; RadiusArrayType mArrayOfAmplifiedRadii; int mNStepSearch; int mSearchControl; int mNumberOfThreads; double mMaxTimeStep; double mSafetyFactor; int mDeltaOption; std::vector<unsigned int> mElementPartition; ParticleCreatorDestructor::Pointer mpParticleCreatorDestructor; DEM_FEM_Search::Pointer mpDemFemSearch; SpatialSearch::Pointer mpSpSearch; bool mDoSearchNeighbourElements; VectorResultConditionsContainerType mRigidFaceResults; VectorDistanceType mRigidFaceResultsDistances; std::vector<unsigned int> mConditionPartition; ModelPart *mpFem_model_part; ModelPart *mpDem_model_part; ModelPart *mpInlet_model_part; ModelPart *mpContact_model_part; ModelPart *mpCluster_model_part; ModelPart *mpRigidBody_model_part; std::vector<SphericParticle*> mListOfSphericParticles; std::vector<SphericParticle*> mListOfGhostSphericParticles; }; // Class ExplicitSolverStrategy } // namespace Kratos. #endif // KRATOS_EXPLICIT_SOLVER_STRATEGY defined
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include <deque> #include <memory> #include <string> #include <vector> namespace llvm { class APSInt; template <typename ValueT> struct DenseMapInfo; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OverloadCandidate; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; /// Keeps track of expected type during expression parsing. The type is tied to /// a particular token, all functions that update or consume the type take a /// start location of the token they are looking at as a parameter. This allows /// to avoid updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder() = default; explicit PreferredTypeBuilder(QualType Type) : Type(Type) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); QualType get(SourceLocation Tok) const { if (Tok == ExpectedLoc) return Type; return QualType(); } private: /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; }; /// Sema - This implements semantic analysis and AST building for C. class Sema { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions FPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; void Act(SourceLocation PragmaLocation, PragmaClangSectionAction Action, StringLiteral* Name); }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value); // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispAttr::Mode> VtorDispStack; // #pragma pack. // Sentinel to represent when the stack is set to mac68k alignment. static const unsigned kMac68kAlignmentSentinel = ~0U; PragmaStack<unsigned> PackStack; // The current #pragma pack values and locations at each #include. struct PackIncludeState { unsigned CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<PackIncludeState, 8> PackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. The /// element type here is ExprWithCleanups::Object. SmallVector<BlockDecl*, 8> ExprCleanupObjects; /// Store a list of either DeclRefExprs or MemberExprs /// that contain a reference to a variable (constant) that may or may not /// be odr-used in this Expr, and we won't know until all lvalue-to-rvalue /// and discarded value conversions have been applied to all subexpressions /// of the enclosing full expression. This is cleared at the end of each /// full expression. llvm::SmallPtrSet<Expr*, 2> MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> PreallocatedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; /// All the members seen during a class definition which were both /// explicitly defaulted and had explicitly-specified exception /// specifications, along with the function type containing their /// user-specified exception specification. Those exception specifications /// were overridden with the default specifications, but we still need to /// check whether they are compatible with the default specification, and /// we can't do that until the nesting set of class definitions is complete. SmallVector<std::pair<CXXMethodDecl*, const FunctionProtoType*>, 2> DelayedDefaultedMemberExceptionSpecs; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// A flag to indicate that we're in a context that permits abstract /// references to fields. This is really a bool AllowAbstractFieldReference; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// Whether we are in a decltype expression. bool IsDecltype; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; llvm::SmallPtrSet<Expr*, 2> SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// The context information used to mangle lambda expressions /// and block literals within this context. /// /// This mangling information is allocated lazily, since most contexts /// do not have lambda expressions or block literals. std::unique_ptr<MangleNumberingContext> MangleNumbering; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), MangleNumbering(), ExprContext(ExprContext) {} /// Retrieve the mangling numbering context, used to consistently /// number constructs like lambdas for mangling. MangleNumberingContext &getMangleNumberingContext(ASTContext &Ctx); bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated; } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. /// \param[out] ManglingContextDecl - Returns the ManglingContextDecl /// associated with the context, if relevant. MangleNumberingContext *getCurrentMangleNumberContext( const DeclContext *DC, Decl *&ManglingContextDecl); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. TranslationUnitKind TUKind; llvm::BumpPtrAllocator BumpAlloc; /// The number of SFINAE diagnostics that have been trapped. unsigned NumSFINAEErrors; typedef llvm::DenseMap<ParmVarDecl *, llvm::TinyPtrVector<ParmVarDecl *>> UnparsedDefaultArgInstantiationsMap; /// A mapping from parameters with unparsed default arguments to the /// set of instantiations of each parameter. /// /// This mapping is a temporary data structure used when parsing /// nested class templates or nested classes of class templates, /// where we might end up instantiating an inner class before the /// default arguments of its methods have been parsed. UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations; // Contains the locations of the beginning of unparsed default // argument locations. llvm::DenseMap<ParmVarDecl *, SourceLocation> UnparsedDefaultArgLocs; /// UndefinedInternals - all the used, undefined objects which require a /// definition in this translation unit. llvm::MapVector<NamedDecl *, SourceLocation> UndefinedButUsed; /// Determine if VD, which must be a variable or function, is an external /// symbol that nonetheless can't be referenced from outside this translation /// unit because its type has no linkage and it's not extern "C". bool isExternalWithNoLinkageType(ValueDecl *VD); /// Obtain a sorted list of functions that are undefined but ODR-used. void getUndefinedButUsed( SmallVectorImpl<std::pair<NamedDecl *, SourceLocation> > &Undefined); /// Retrieves list of suspicious delete-expressions that will be checked at /// the end of translation unit. const llvm::MapVector<FieldDecl *, DeleteLocs> & getMismatchingDeleteExpressions() const; typedef std::pair<ObjCMethodList, ObjCMethodList> GlobalMethods; typedef llvm::DenseMap<Selector, GlobalMethods> GlobalMethodPool; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the FP_CONTRACT state on entry/exit of compound /// statements. class FPContractStateRAII { public: FPContractStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.FPFeatures) {} ~FPContractStateRAII() { S.FPFeatures = OldFPFeaturesState; } private: Sema& S; FPOptions OldFPFeaturesState; }; void addImplicitTypedef(StringRef Name, QualType T); public: Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind = TU_Complete, CodeCompleteConsumer *CompletionConsumer = nullptr); ~Sema(); /// Perform initialization that occurs after the parser has been /// initialized but before it parses anything. void Initialize(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getFPOptions() { return FPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. SemaDiagnosticBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class SemaDiagnosticBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: SemaDiagnosticBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) { } // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~SemaDiagnosticBuilder is a safe no-op // in that case anwyay. SemaDiagnosticBuilder(const SemaDiagnosticBuilder&) = default; ~SemaDiagnosticBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First flush the underlying // DiagnosticBuilder data, and clear the diagnostic builder itself so it // won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. FlushCounts(); Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template<typename T> friend const SemaDiagnosticBuilder &operator<<( const SemaDiagnosticBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } }; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) { DiagnosticBuilder DB = Diags.Report(Loc, DiagID); return SemaDiagnosticBuilder(DB, *this, DiagID); } /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic& PD); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; void emitAndClearUnusedLocalTypedefWarnings(); void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K); void PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, const BlockExpr *blkExpr = nullptr); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool isCurCompoundStmtAStmtExpr() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity); QualType BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, Expr *ArraySize, unsigned Quals, SourceRange Brackets, DeclarationName Entity); QualType BuildVectorType(QualType T, Expr *VecSize, SourceLocation AttrLoc); QualType BuildExtVectorType(QualType T, Expr *ArraySize, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Expr *E); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, llvm::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, llvm::index_sequence_for<Ts...>()); DB << T; } }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, TypeDiagnoser *Diagnoser); struct ModuleScope { clang::Module *Module = nullptr; bool ModuleInterface = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return !D->isHidden() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T) { return !RequireCompleteTypeImpl(Loc, T, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); QualType BuildTypeofExprType(Expr *E, SourceLocation Loc); /// If AsUnevaluated is false, E is treated as though it were an evaluated /// context, such as when building a type for decltype(auto). QualType BuildDecltypeType(Expr *E, SourceLocation Loc, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { NC_Unknown, NC_Error, NC_Keyword, NC_Type, NC_Expression, NC_NestedNameSpecifier, NC_TypeTemplate, NC_VarTemplate, NC_FunctionTemplate }; class NameClassification { NameClassificationKind Kind; ExprResult Expr; TemplateName Template; ParsedType Type; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ExprResult Expr) : Kind(NC_Expression), Expr(Expr) {} NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification NestedNameSpecifier() { return NameClassification(NC_NestedNameSpecifier); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } ExprResult getExpression() const { assert(Kind == NC_Expression); return Expr; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param IsAddressOfOperand True if this name is the operand of a unary /// address of ('&') expression, assuming it is classified as an /// expression. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, bool IsAddressOfOperand, std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S); bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info); bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId); void diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals, SourceLocation FallbackLoc, SourceLocation ConstQualLoc = SourceLocation(), SourceLocation VolatileQualLoc = SourceLocation(), SourceLocation RestrictQualLoc = SourceLocation(), SourceLocation AtomicQualLoc = SourceLocation(), SourceLocation UnalignedQualLoc = SourceLocation()); static bool adjustContextForLocalExternDecl(DeclContext *&DC); void DiagnoseFunctionSpecifiers(const DeclSpec &DS); NamedDecl *getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R); NamedDecl *getShadowedDeclaration(const VarDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *&Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); bool CheckConstexprFunctionDecl(const FunctionDecl *FD); bool CheckConstexprFunctionBody(const FunctionDecl *FD, Stmt *Body); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); Decl *ActOnParamDeclarator(Scope *S, Declarator &D); ParmVarDecl *BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T); ParmVarDecl *CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC); void ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc, Expr *defarg); void ActOnParamUnparsedDefaultArgument(Decl *param, SourceLocation EqualLoc, SourceLocation ArgLoc); void ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc); bool SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); void ActOnUninitializedDecl(Decl *dcl); void ActOnInitializerError(Decl *Dcl); void ActOnPureSpecifier(Decl *D, SourceLocation PureSpecLoc); void ActOnCXXForRangeDecl(Decl *D); StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs, SourceLocation AttrEnd); void SetDeclDeleted(Decl *dcl, SourceLocation DelLoc); void SetDeclDefaulted(Decl *dcl, SourceLocation DefaultLoc); void CheckStaticLocalForDllExport(VarDecl *VD); void FinalizeDeclaration(Decl *D); DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef<Decl *> Group); DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef<Decl *> Group); /// Should be called on all declarations that might have attached /// documentation comments. void ActOnDocumentableDecl(Decl *D); void ActOnDocumentableDecls(ArrayRef<Decl *> Group); void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls); void CheckForFunctionRedefinition( FunctionDecl *FD, const FunctionDecl *EffectiveDefinition = nullptr, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnStartOfFunctionDef(Scope *S, Decl *D, SkipBodyInfo *SkipBody = nullptr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' Partition, ///< 'module partition X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path); /// The parser has processed a module import declaration. /// /// \param AtLoc The location of the '@' symbol, if any. /// /// \param ImportLoc The location of the 'import' keyword. /// /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation AtLoc, SourceLocation ImportLoc, ModuleIdPath Path); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// We've found a use of a template specialization that would select a /// partial specialization. Check that the partial specialization is visible, /// and diagnose if not. void checkPartialSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); Decl *ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, MultiTemplateParamsArg TempParamLists); TypeResult ActOnDependentTag(Scope *S, unsigned TagSpec, TagUseKind TUK, const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation TagLoc, SourceLocation NameLoc); void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl<Decl *> &Decls); Decl *ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth); FieldDecl *HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS); MSPropertyDecl *HandleMSProperty(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS, const ParsedAttr &MSPropertyAttr); FieldDecl *CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D = nullptr); bool CheckNontrivialField(FieldDecl *FD); void DiagnoseNontrivial(const CXXRecordDecl *Record, CXXSpecialMember CSM); enum TrivialABIHandling { /// The triviality of a method unaffected by "trivial_abi". TAH_IgnoreTrivialABI, /// The triviality of a method affected by "trivial_abi". TAH_ConsiderTrivialABI }; bool SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM, TrivialABIHandling TAH = TAH_IgnoreTrivialABI, bool Diagnose = false); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD); void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); DeclContext *getContainingDC(DeclContext *DC); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// Make the given externally-produced declaration visible at the /// top level scope. /// /// \param D The externally-produced declaration to push. /// /// \param Name The name of the externally-produced declaration. void pushExternalDeclIntoScope(NamedDecl *D, DeclarationName Name); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr *mergeAvailabilityAttr( NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority, unsigned AttrSpellingListIndex); TypeVisibilityAttr *mergeTypeVisibilityAttr(Decl *D, SourceRange Range, TypeVisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); VisibilityAttr *mergeVisibilityAttr(Decl *D, SourceRange Range, VisibilityAttr::VisibilityType Vis, unsigned AttrSpellingListIndex); UuidAttr *mergeUuidAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex, StringRef Uuid); DLLImportAttr *mergeDLLImportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); DLLExportAttr *mergeDLLExportAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, unsigned AttrSpellingListIndex, MSInheritanceAttr::Spelling SemanticSpelling); FormatAttr *mergeFormatAttr(Decl *D, SourceRange Range, IdentifierInfo *Format, int FormatIdx, int FirstArg, unsigned AttrSpellingListIndex); SectionAttr *mergeSectionAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex); CodeSegAttr *mergeCodeSegAttr(Decl *D, SourceRange Range, StringRef Name, unsigned AttrSpellingListIndex); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, SourceRange Range, IdentifierInfo *Ident, unsigned AttrSpellingListIndex); MinSizeAttr *mergeMinSizeAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); NoSpeculativeLoadHardeningAttr * mergeNoSpeculativeLoadHardeningAttr(Decl *D, const NoSpeculativeLoadHardeningAttr &AL); SpeculativeLoadHardeningAttr * mergeSpeculativeLoadHardeningAttr(Decl *D, const SpeculativeLoadHardeningAttr &AL); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, SourceRange Range, unsigned AttrSpellingListIndex); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const ParsedAttr &AL); CommonAttr *mergeCommonAttr(Decl *D, const CommonAttr &AL); void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK = AMK_Redeclaration); void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls); bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld); bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld); void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old); void MergeVarDecl(VarDecl *New, LookupResult &Previous); void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld); void MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old); bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn); void notePreviousDefinition(const NamedDecl *Old, SourceLocation New); bool MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old, Scope *S); // AssignmentAction - This is used by all the assignment diagnostic functions // to represent what is actually causing the operation enum AssignmentAction { AA_Assigning, AA_Passing, AA_Returning, AA_Converting, AA_Initializing, AA_Sending, AA_Casting, AA_Passing_CFAudited }; /// C++ Overloading. enum OverloadKind { /// This is a legitimate overload: the existing declarations are /// functions or function templates with different signatures. Ovl_Overload, /// This is not an overload because the signature exactly matches /// an existing declaration. Ovl_Match, /// This is not an overload because the lookup results contain a /// non-function. Ovl_NonFunction }; OverloadKind CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &OldDecls, NamedDecl *&OldDecl, bool IsForUsingDecl); bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs = true); /// Checks availability of the function depending on the current /// function context.Inside an unavailable function,unavailability is ignored. /// /// \returns true if \p FD is unavailable and current context is inside /// an available function, false otherwise. bool isFunctionConsideredUnavailable(FunctionDecl *FD); ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, bool AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(CanQualType Param, CanQualType Arg); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const VarDecl *NRVOCandidate, QualType ResultType, Expr *Value, bool AllowNRVO = true); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_NewExpr, ///< Constant expression in a noptr-new-declarator. CCEK_ConstexprIf ///< Condition in a constexpr if statement. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL); bool CheckNonDependentConversions(FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}); void AddConversionCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet& CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, SourceRange OpRange = SourceRange()); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate(NamedDecl *Found, FunctionDecl *Fn, QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfOnlyViableOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfOnlyViableOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplate }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing); bool isKnownName(StringRef name); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr(Expr *E, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr(Expr *E, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(E, nullptr, Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, VarDecl *InitDecl = nullptr, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), Filter); } ExprResult CorrectDelayedTyposInExpr(ExprResult ER, llvm::function_ref<ExprResult(Expr *)> Filter) { return CorrectDelayedTyposInExpr(ER, nullptr, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Determine if type T is a valid subject for a nonnull and similar /// attributes. By default, we look through references (the behavior used by /// nonnull), but if the second parameter is true, then we treat a reference /// type as valid. bool isValidPointerAttrType(QualType T, bool RefOkay = false); bool CheckRegparmAttr(const ParsedAttr &attr, unsigned &value); bool CheckCallingConvAttr(const ParsedAttr &attr, CallingConv &CC, const FunctionDecl *FD = nullptr); bool CheckAttrTarget(const ParsedAttr &CurrAttr); bool CheckAttrNoArgs(const ParsedAttr &CurrAttr); bool checkStringLiteralArgumentAttr(const ParsedAttr &Attr, unsigned ArgNum, StringRef &Str, SourceLocation *ArgLocation = nullptr); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceAttr::Spelling SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType &T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Stmt attributes - this routine is the top level dispatcher. StmtResult ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesView &Attrs, SourceRange Range); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// A RAII object to enter scope of a compound statement. class CompoundScopeRAII { public: CompoundScopeRAII(Sema &S, bool IsStmtExpr = false) : S(S) { S.ActOnStartOfCompoundStmt(IsStmtExpr); } ~CompoundScopeRAII() { S.ActOnFinishOfCompoundStmt(); } private: Sema &S; }; /// An RAII helper that pops function a function scope on exit. struct FunctionScopeRAII { Sema &S; bool Active; FunctionScopeRAII(Sema &S) : S(S), Active(true) {} ~FunctionScopeRAII() { if (Active) S.PopFunctionScopeInfo(); } void disable() { Active = false; } }; StmtResult ActOnDeclStmt(DeclGroupPtrTy Decl, SourceLocation StartLoc, SourceLocation EndLoc); void ActOnForEachDeclStmt(DeclGroupPtrTy Decl); StmtResult ActOnForEachLValueExpr(Expr *E); ExprResult ActOnCaseExpr(SourceLocation CaseLoc, ExprResult Val); StmtResult ActOnCaseStmt(SourceLocation CaseLoc, ExprResult LHS, SourceLocation DotDotDotLoc, ExprResult RHS, SourceLocation ColonLoc); void ActOnCaseStmtBody(Stmt *CaseStmt, Stmt *SubStmt); StmtResult ActOnDefaultStmt(SourceLocation DefaultLoc, SourceLocation ColonLoc, Stmt *SubStmt, Scope *CurScope); StmtResult ActOnLabelStmt(SourceLocation IdentLoc, LabelDecl *TheDecl, SourceLocation ColonLoc, Stmt *SubStmt); StmtResult ActOnAttributedStmt(SourceLocation AttrLoc, ArrayRef<const Attr*> Attrs, Stmt *SubStmt); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, bool IsConstexpr, Stmt *InitStmt, ConditionResult Cond, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, Stmt *InitStmt, ConditionResult Cond); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, ConditionResult Cond, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); enum CopyElisionSemanticsKind { CES_Strict = 0, CES_AllowParameters = 1, CES_AllowDifferentTypes = 2, CES_AllowExceptionVariables = 4, CES_FormerDefault = (CES_AllowParameters), CES_Default = (CES_AllowParameters | CES_AllowDifferentTypes), CES_AsIfByStdMove = (CES_AllowParameters | CES_AllowDifferentTypes | CES_AllowExceptionVariables), }; VarDecl *getCopyElisionCandidate(QualType ReturnType, Expr *E, CopyElisionSemanticsKind CESK); bool isCopyElisionCandidate(QualType ReturnType, const VarDecl *VD, CopyElisionSemanticsKind CESK); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// Emit \p DiagID if statement located on \p StmtLoc has a suspicious null /// statement as a \p Body, and it is located on the same line. /// /// This helps prevent bugs due to typos, such as: /// if (condition); /// do_stuff(); void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID); /// Warn if a for/while loop statement \p S, which is followed by /// \p PossibleBody, has a suspicious null statement as a body. void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody); /// Warn if a value is moved to itself. void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc); /// Warn if we're implicitly casting from a _Nullable pointer type to a /// _Nonnull one. void diagnoseNullableToNonnullConversion(QualType DstType, QualType SrcType, SourceLocation Loc); /// Warn when implicitly casting 0 to nullptr. void diagnoseZeroToNullptrConversion(CastKind Kind, const Expr *E); ParsingDeclState PushParsingDeclaration(sema::DelayedDiagnosticPool &pool) { return DelayedDiagnostics.push(pool); } void PopParsingDeclaration(ParsingDeclState state, Decl *decl); typedef ProcessingContextState ParsingClassState; ParsingClassState PushParsingClass() { return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); std::string getDeletedOrUnavailableSuffix(const FunctionDecl *FD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void UpdateMarkingForLValueToRValue(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, std::unique_ptr<CorrectionCandidateCallback> CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); ExprResult BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLoc, Expr *Length, SourceLocation RBLoc); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation Loc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); // "({..})" void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- Clang Extensions ----------------------===// /// __builtin_convertvector(...) ExprResult ActOnConvertVectorExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- OpenCL Features -----------------------===// /// __builtin_astype(...) ExprResult ActOnAsTypeExpr(Expr *E, ParsedType ParsedDestTy, SourceLocation BuiltinLoc, SourceLocation RParenLoc); //===---------------------------- C++ Features --------------------------===// // Act on C++ namespaces Decl *ActOnStartNamespaceDef(Scope *S, SourceLocation InlineLoc, SourceLocation NamespaceLoc, SourceLocation IdentLoc, IdentifierInfo *Ident, SourceLocation LBrace, const ParsedAttributesView &AttrList, UsingDirectiveDecl *&UsingDecl); void ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace); NamespaceDecl *getStdNamespace() const; NamespaceDecl *getOrCreateStdNamespace(); NamespaceDecl *lookupStdExperimentalNamespace(); CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(UsingDecl *UD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, UsingDecl *UD, NamedDecl *Target, UsingShadowDecl *PrevDecl); bool CheckUsingDeclRedeclaration(SourceLocation UsingLoc, bool HasTypenameKeyword, const CXXScopeSpec &SS, SourceLocation NameLoc, const LookupResult &Previous); bool CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename, const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, SourceLocation NameLoc); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation); NamedDecl *BuildUsingPackDecl(NamedDecl *InstantiatedFrom, ArrayRef<NamedDecl *> Expansions); bool CheckInheritingConstructorUsingDecl(UsingDecl *UD); /// Given a derived-class using shadow declaration for a constructor and the /// correspnding base class constructor, find or create the implicit /// synthesized derived class constructor to use for this initialization. CXXConstructorDecl * findInheritingConstructor(SourceLocation Loc, CXXConstructorDecl *BaseCtor, ConstructorUsingShadowDecl *DerivedShadow); Decl *ActOnUsingDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation TypenameLoc, CXXScopeSpec &SS, UnqualifiedId &Name, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Determine what sort of exception specification a defaulted /// copy constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDefaultCtorExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// default constructor of a class will have, and whether the parameter /// will be const. ImplicitExceptionSpecification ComputeDefaultedCopyCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// copy assignment operator of a class will have, and whether the /// parameter will be const. ImplicitExceptionSpecification ComputeDefaultedCopyAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// constructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveCtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted move /// assignment operator of a class will have. ImplicitExceptionSpecification ComputeDefaultedMoveAssignmentExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification a defaulted /// destructor of a class will have. ImplicitExceptionSpecification ComputeDefaultedDtorExceptionSpec(CXXMethodDecl *MD); /// Determine what sort of exception specification an inheriting /// constructor of a class will have. ImplicitExceptionSpecification ComputeInheritingCtorExceptionSpec(SourceLocation Loc, CXXConstructorDecl *CD); /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(SourceLocation NoexceptLoc, Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, MultiExprArg ArgsPtr, SourceLocation Loc, SmallVectorImpl<Expr*> &ConvertedArgs, bool AllowExplicit = false, bool IsListInitialization = false); ParsedType getInheritingConstructorName(CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo &Name); ParsedType getConstructorName(IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, bool EnteringContext); ParsedType getDestructorName(SourceLocation TildeLoc, IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext); ParsedType getDestructorTypeForDecltype(const DeclSpec &DS, ParsedType ObjectType); // Checks that reinterpret casts don't have undefined behavior. void CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType, bool IsDereference, SourceRange Range); /// ActOnCXXNamedCast - Parse {dynamic,static,reinterpret,const}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Expr *ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, bool IsConstexprSpecified); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Build the implicit field for an init-capture. FieldDecl *buildInitCaptureField(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); void CheckCompletedCXXClass(CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(Decl *D); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Scope *S, Decl *Template); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD); void CheckExplicitlyDefaultedMemberExceptionSpec(CXXMethodDecl *MD, const FunctionProtoType *T); void CheckDelayedMemberExceptionSpecs(); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbigiousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl, AccessSpecifier access, QualType objectType); void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true); bool LookupTemplateName(LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, SourceLocation TemplateKWLoc = SourceLocation()); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnDependentTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TemplateTypeParmDecl *Param, TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression, UPPC_Block }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *&Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate(FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *P, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool Subst(const TemplateArgumentLoc *Args, unsigned NumArgs, TemplateArgumentListInfo &Result, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, void *InsertPos, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation( SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool ConversionToObjCStringLiteralCheck(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaPack(PragmaPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispAttr::Mode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, DeclaratorDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(LangOptions::FPContractModeKind FPC); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(LangOptions::FEnvAccessModeKind FPC); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// FreePackedContext - Deallocate and null out PackContext. void FreePackedContext(); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex, bool IsPackExpansion); void AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *T, unsigned SpellingListIndex, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, Expr *OE, unsigned SpellingListIndex); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, unsigned SpellingListIndex); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, unsigned SpellingListIndex); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, Expr *MinBlocks, unsigned SpellingListIndex); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, unsigned SpellingListIndex, bool InInstantiation = false); void AddParameterABIAttr(SourceRange AttrRange, Decl *D, ParameterABI ABI, unsigned SpellingListIndex); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex, RetainOwnershipKind K, bool IsTemplateInstantiation); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); //===--------------------------------------------------------------------===// // C++ Coroutines TS // bool ActOnCoroutineBodyStart(Scope *S, SourceLocation KwLoc, StringRef Keyword); ExprResult ActOnCoawaitExpr(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult ActOnCoyieldExpr(Scope *S, SourceLocation KwLoc, Expr *E); StmtResult ActOnCoreturnStmt(Scope *S, SourceLocation KwLoc, Expr *E); ExprResult BuildResolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); ExprResult BuildUnresolvedCoawaitExpr(SourceLocation KwLoc, Expr *E, UnresolvedLookupExpr* Lookup); ExprResult BuildCoyieldExpr(SourceLocation KwLoc, Expr *E); StmtResult BuildCoreturnStmt(SourceLocation KwLoc, Expr *E, bool IsImplicit = false); StmtResult BuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs); bool buildCoroutineParameterMoves(SourceLocation Loc); VarDecl *buildCoroutinePromise(SourceLocation Loc); void CheckCompletedCoroutineBody(FunctionDecl *FD, Stmt *&Body); ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc); //===--------------------------------------------------------------------===// // OpenCL extensions. // private: std::string CurrOpenCLExtension; /// Extensions required by an OpenCL type. llvm::DenseMap<const Type*, std::set<std::string>> OpenCLTypeExtMap; /// Extensions required by an OpenCL declaration. llvm::DenseMap<const Decl*, std::set<std::string>> OpenCLDeclExtMap; public: llvm::StringRef getCurrentOpenCLExtension() const { return CurrOpenCLExtension; } /// Check if a function declaration \p FD associates with any /// extensions present in OpenCLDeclExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromDeclExtMap(FunctionDecl *FD); /// Check if a function type \p FT associates with any /// extensions present in OpenCLTypeExtMap and if so return the /// extension(s) name(s). std::string getOpenCLExtensionsFromTypeExtMap(FunctionType *FT); /// Find an extension in an appropriate extension map and return its name template<typename T, typename MapT> std::string getOpenCLExtensionsFromExtMap(T* FT, MapT &Map); void setCurrentOpenCLExtension(llvm::StringRef Ext) { CurrOpenCLExtension = Ext; } /// Set OpenCL extensions for a type which can only be used when these /// OpenCL extensions are enabled. If \p Exts is empty, do nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForType(QualType T, llvm::StringRef Exts); /// Set OpenCL extensions for a declaration which can only be /// used when these OpenCL extensions are enabled. If \p Exts is empty, do /// nothing. /// \param Exts A space separated list of OpenCL extensions. void setOpenCLExtensionForDecl(Decl *FD, llvm::StringRef Exts); /// Set current OpenCL extensions for a type which can only be used /// when these OpenCL extensions are enabled. If current OpenCL extension is /// empty, do nothing. void setCurrentOpenCLExtensionForType(QualType T); /// Set current OpenCL extensions for a declaration which /// can only be used when these OpenCL extensions are enabled. If current /// OpenCL extension is empty, do nothing. void setCurrentOpenCLExtensionForDecl(Decl *FD); bool isOpenCLDisabledDecl(Decl *FD); /// Check if type \p T corresponding to declaration specifier \p DS /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledTypeDeclSpec(const DeclSpec &DS, QualType T); /// Check if declaration \p D used by expression \p E /// is disabled due to required OpenCL extensions being disabled. If so, /// emit diagnostics. /// \return true if type is disabled. bool checkOpenCLDisabledDecl(const NamedDecl &D, const Expr &E); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; /// Number of nested '#pragma omp declare target' directives. unsigned DeclareTargetNestingLevel = 0; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Check whether we're allowed to call Callee from the current function. void checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); /// Checks if a type or a declaration is disabled due to the owning extension /// being disabled, and emits diagnostic messages if it is disabled. /// \param D type or declaration to be checked. /// \param DiagLoc source location for the diagnostic message. /// \param DiagInfo information to be emitted for the diagnostic message. /// \param SrcRange source range of the declaration. /// \param Map maps type or declaration to the extensions. /// \param Selector selects diagnostic message: 0 for type and 1 for /// declaration. /// \return true if the type or declaration is disabled. template <typename T, typename DiagLocT, typename DiagInfoT, typename MapT> bool checkOpenCLDisabledTypeOrDecl(T D, DiagLocT DiagLoc, DiagInfoT DiagInfo, MapT &Map, unsigned Selector = 0, SourceRange SrcRange = SourceRange()); public: /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. OMPDeclareMapperDecl *ActOnOpenMPDeclareMapperDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. void ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); /// Called at the end of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, ArrayRef<OMPClause *> ClauseList); /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc); /// Called at the end of target region i.e. '#pragme omp end declare target'. void ActOnFinishOpenMPDeclareTargetDirective(); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OMPDeclareTargetDeclAttr::MapTypeTy MT, NamedDeclSetType &SameDirectiveDecls); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return DeclareTargetNestingLevel > 0; } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return true if (un)supported features for the current target should be /// diagnosed if OpenMP (offloading) is enabled. bool shouldDiagnoseTargetSupportFromOpenMP() const { return !getLangOpts().OpenMPIsDevice || isInOpenMPDeclareTargetContext() || isInOpenMPTargetExecutionDirective(); } /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// End of OpenMP region. /// /// \param S Statement associated with the current OpenMP region. /// \param Clauses List of clauses for the current OpenMP region. /// /// \returns Statement for finished OpenMP region. StmtResult ActOnOpenMPRegionEnd(StmtResult S, ArrayRef<OMPClause *> Clauses); StmtResult ActOnOpenMPExecutableDirective( OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); using VarsWithInheritedDSAType = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 4>; /// Called on well-formed '\#pragma omp simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'safelen' clause. OMPClause *ActOnOpenMPSafelenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'simdlen' clause. OMPClause *ActOnOpenMPSimdlenClause(Expr *Length, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *TailExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, OpenMPLinearClauseKind LinKind, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation DepLinMapLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause * ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause *ActOnOpenMPToClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'from' clause. OMPClause *ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// The kind of conversion being performed. enum CheckedConversionKind { /// An implicit conversion. CCK_ImplicitConversion, /// A C-style cast. CCK_CStyleCast, /// A functional-style cast. CCK_FunctionalCast, /// A cast other than a C-style cast. CCK_OtherCast, /// A conversion for an operand of a builtin overloaded operator. CCK_ForBuiltinOverloadedOp }; static bool isCast(CheckedConversionKind CCK) { return CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast || CCK == CCK_OtherCast; } /// ImpCastExprToType - If Expr is not of type 'Type', insert an implicit /// cast. If there is already an implicit cast, merge into the existing one. /// If isLvalue, the result of the cast is an lvalue. ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK = VK_RValue, const CXXCastPath *BasePath = nullptr, CheckedConversionKind CCK = CCK_ImplicitConversion); /// ScalarTypeToBooleanCastKind - Returns the cast kind corresponding /// to the conversion from scalar type ScalarTy to the Boolean type. static CastKind ScalarTypeToBooleanCastKind(QualType ScalarTy); /// IgnoredValueConversions - Given that an expression's result is /// syntactically ignored, perform any conversions that are /// required. ExprResult IgnoredValueConversions(Expr *E); // UsualUnaryConversions - promotes integers (C99 6.3.1.1p2) and converts // functions and arrays to their respective pointers (C99 6.3.2.1). ExprResult UsualUnaryConversions(Expr *E); /// CallExprUnaryConversions - a special case of an unary conversion /// performed on a function designator of a call expression. ExprResult CallExprUnaryConversions(Expr *E); // DefaultFunctionArrayConversion - converts functions and arrays // to their respective pointers (C99 6.3.2.1). ExprResult DefaultFunctionArrayConversion(Expr *E, bool Diagnose = true); // DefaultFunctionArrayLvalueConversion - converts functions and // arrays to their respective pointers and performs the // lvalue-to-rvalue conversion. ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose = true); // DefaultLvalueConversion - performs lvalue-to-rvalue conversion on // the operand. This is DefaultFunctionArrayLvalueConversion, // except that it assumes the operand isn't of function or array // type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, bool IsCompAssign = false); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// Incompatible - We reject this conversion outright, it is invalid to /// represent it in the AST. Incompatible }; /// DiagnoseAssignmentResult - Emit a diagnostic, if required, for the /// assignment conversion type specified by ConvTy. This returns true if the /// conversion was invalid or false if the conversion was accepted. bool DiagnoseAssignmentResult(AssignConvertType ConvTy, SourceLocation Loc, QualType DstType, QualType SrcType, Expr *SrcExpr, AssignmentAction Action, bool *Complained = nullptr); /// IsValueInFlagEnum - Determine if a value is allowed as part of a flag /// enum. If AllowMask is true, then we also allow the complement of a valid /// value, to be used as a mask. bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const; /// DiagnoseAssignmentEnum - Warn if assignment to enum is a constant /// integer not in the range of enum values. void DiagnoseAssignmentEnum(QualType DstType, QualType SrcType, Expr *SrcExpr); /// CheckAssignmentConstraints - Perform type checking for assignment, /// argument passing, variable initialization, and function return values. /// C99 6.5.16. AssignConvertType CheckAssignmentConstraints(SourceLocation Loc, QualType LHSType, QualType RHSType); /// Check assignment constraints and optionally prepare for a conversion of /// the RHS to the LHS type. The conversion is prepared for if ConvertRHS /// is true. AssignConvertType CheckAssignmentConstraints(QualType LHSType, ExprResult &RHS, CastKind &Kind, bool ConvertRHS = true); /// Check assignment constraints for an assignment of RHS to LHSType. /// /// \param LHSType The destination type for the assignment. /// \param RHS The source expression for the assignment. /// \param Diagnose If \c true, diagnostics may be produced when checking /// for assignability. If a diagnostic is produced, \p RHS will be /// set to ExprError(). Note that this function may still return /// without producing a diagnostic, even for an invalid assignment. /// \param DiagnoseCFAudited If \c true, the target is a function parameter /// in an audited Core Foundation API and does not need to be checked /// for ARC retain issues. /// \param ConvertRHS If \c true, \p RHS will be updated to model the /// conversions necessary to perform the assignment. If \c false, /// \p Diagnose must also be \c false. AssignConvertType CheckSingleAssignmentConstraints( QualType LHSType, ExprResult &RHS, bool Diagnose = true, bool DiagnoseCFAudited = false, bool ConvertRHS = true); // If the lhs type is a transparent union, check whether we // can initialize the transparent union with the given expression. AssignConvertType CheckTransparentUnionArgumentConstraints(QualType ArgType, ExprResult &RHS); bool IsStringLiteralToNonConstPointerConversion(Expr *From, QualType ToType); bool CheckExceptionSpecCompatibility(Expr *From, QualType ToType); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit = false); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, AssignmentAction Action, bool AllowExplicit, ImplicitConversionSequence& ICS); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence& ICS, AssignmentAction Action, CheckedConversionKind CCK = CCK_ImplicitConversion); ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const StandardConversionSequence& SCS, AssignmentAction Action, CheckedConversionKind CCK); ExprResult PerformQualificationConversion( Expr *E, QualType Ty, ExprValueKind VK = VK_RValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, bool &DerivedToBase, bool &ObjCConversion, bool &ObjCLifetimeConversion); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) =0; virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR); virtual ~VerifyICEDiagnoser() { } }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, bool AllowFold = true); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr); /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); /// Diagnostics that are emitted only if we discover that the given function /// must be codegen'ed. Because handling these correctly adds overhead to /// compilation, this is currently only enabled for CUDA compilations. llvm::DenseMap<CanonicalDeclPtr<FunctionDecl>, std::vector<PartialDiagnosticAt>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// A partial call graph maintained during CUDA/OpenMP device code compilation /// to support deferred diagnostics. /// /// Functions are only added here if, at the time they're considered, they are /// not known-emitted. As soon as we discover that a function is /// known-emitted, we remove it and everything it transitively calls from this /// set and add those functions to DeviceKnownEmittedFns. llvm::DenseMap</* Caller = */ CanonicalDeclPtr<FunctionDecl>, /* Callees = */ llvm::MapVector<CanonicalDeclPtr<FunctionDecl>, SourceLocation>> DeviceCallGraph; /// Diagnostic builder for CUDA/OpenMP devices errors which may or may not be /// deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class DeviceDiagBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; DeviceDiagBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S); ~DeviceDiagBuilder(); /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (DeviceDiagBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a DeviceDiagBuilder yourself. operator bool() const { return ImmediateDiag.hasValue(); } template <typename T> friend const DeviceDiagBuilder &operator<<(const DeviceDiagBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiag.hasValue()) *Diag.PartialDiag << Value; return Diag; } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<SemaDiagnosticBuilder> ImmediateDiag; llvm::Optional<PartialDiagnostic> PartialDiag; }; /// Indicate that this function (and thus everything it transtively calls) /// will be codegen'ed, and emit any deferred diagnostics on this function and /// its (transitive) callees. void markKnownEmitted( Sema &S, FunctionDecl *OrigCaller, FunctionDecl *OrigCallee, SourceLocation OrigLoc, const llvm::function_ref<bool(Sema &, FunctionDecl *)> IsKnownEmitted); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current context /// is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. DeviceDiagBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a DeviceDiagBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. DeviceDiagBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID); enum CUDAFunctionTarget { CFT_Device, CFT_Global, CFT_Host, CFT_HostDevice, CFT_InvalidTarget }; /// Determines whether the given function is a CUDA device/host/kernel/etc. /// function. /// /// Use this rather than examining the function's attributes yourself -- you /// will get it wrong. Returns CFT_Host if D is null. CUDAFunctionTarget IdentifyCUDATarget(const FunctionDecl *D, bool IgnoreImplicitHDAttr = false); CUDAFunctionTarget IdentifyCUDATarget(const ParsedAttributesView &Attrs); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas declared inside __device__ or __global__ functions inherit /// the __device__ attribute. Similarly, lambdas inside __host__ __device__ /// functions become __host__ __device__ themselves. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); /// Reports signatures for a call to CodeCompleteConsumer and returns the /// preferred type for the current argument. Returned type can be null. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); void CodeCompleteAfterIf(Scope *S); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, QualType BaseType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckARMBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinCpu(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); public: // Used by C++ template instantiation. ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall); ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc); private: bool SemaBuiltinPrefetch(CallExpr *TheCall); bool SemaBuiltinAllocaWithAlign(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; private: class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedDefaultedMemberExceptionSpecs.empty() && "there shouldn't be any pending delayed defaulted member " "exception specs"); assert(S.DelayedDllExportClasses.empty() && "there shouldn't be any pending delayed DLL export classes"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; decltype(DelayedDefaultedMemberExceptionSpecs) SavedDefaultedMemberExceptionSpecs; decltype(DelayedDllExportClasses) SavedDllExportClasses; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); SavedDefaultedMemberExceptionSpecs.swap( S.DelayedDefaultedMemberExceptionSpecs); SavedDllExportClasses.swap(S.DelayedDllExportClasses); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); }; /// RAII object that enters a new expression evaluation context. class EnterExpressionEvaluationContext { Sema &Actions; bool Entered = true; public: EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other, bool ShouldEnter = true) : Actions(Actions), Entered(ShouldEnter) { if (Entered) Actions.PushExpressionEvaluationContext(NewContext, LambdaContextDecl, ExprContext); } EnterExpressionEvaluationContext( Sema &Actions, Sema::ExpressionEvaluationContext NewContext, Sema::ReuseLambdaContextDecl_t, Sema::ExpressionEvaluationContextRecord::ExpressionKind ExprContext = Sema::ExpressionEvaluationContextRecord::EK_Other) : Actions(Actions) { Actions.PushExpressionEvaluationContext( NewContext, Sema::ReuseLambdaContextDecl, ExprContext); } enum InitListTag { InitList }; EnterExpressionEvaluationContext(Sema &Actions, InitListTag, bool ShouldEnter = true) : Actions(Actions), Entered(false) { // In C++11 onwards, narrowing checks are performed on the contents of // braced-init-lists, even when they occur within unevaluated operands. // Therefore we still need to instantiate constexpr functions used in such // a context. if (ShouldEnter && Actions.isUnevaluatedContext() && Actions.getLangOpts().CPlusPlus11) { Actions.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::UnevaluatedList); Entered = true; } } ~EnterExpressionEvaluationContext() { if (Entered) Actions.PopExpressionEvaluationContext(); } }; DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, Sema::TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info); /// Contains a late templated function. /// Will be parsed at the end of the translation unit, used by Sema & Parser. struct LateParsedTemplate { CachedTokens Toks; /// The template function declaration to be late parsed. Decl *D; }; } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getRawEncoding()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
nstream-memcpy-target.c
/// /// Copyright (c) 2019, Intel Corporation /// /// Redistribution and use in source and binary forms, with or without /// modification, are permitted provided that the following conditions /// are met: /// /// * Redistributions of source code must retain the above copyright /// notice, this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above /// copyright notice, this list of conditions and the following /// disclaimer in the documentation and/or other materials provided /// with the distribution. /// * Neither the name of Intel Corporation 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 OWNER 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. ////////////////////////////////////////////////////////////////////// /// /// NAME: nstream /// /// PURPOSE: To compute memory bandwidth when adding a vector of a given /// number of double precision values to the scalar multiple of /// another vector of the same length, and storing the result in /// a third vector. /// /// USAGE: The program takes as input the number /// of iterations to loop over the triad vectors and /// the length of the vectors. /// /// <progname> <# iterations> <vector length> /// /// The output consists of diagnostics to make sure the /// algorithm worked, and of timing statistics. /// /// NOTES: Bandwidth is determined as the number of words read, plus the /// number of words written, times the size of the words, divided /// by the execution time. For a vector length of N, the total /// number of words read and written is 4*N*sizeof(double). /// /// /// HISTORY: This code is loosely based on the Stream benchmark by John /// McCalpin, but does not follow all the Stream rules. Hence, /// reported results should not be associated with Stream in /// external publications /// /// Converted to C++11 by Jeff Hammond, November 2017. /// Converted to C11 by Jeff Hammond, February 2019. /// ////////////////////////////////////////////////////////////////////// #pragma omp requires unified_address #include "prk_util.h" #include "prk_openmp.h" int main(int argc, char * argv[]) { printf("Parallel Research Kernels version %d\n", PRKVERSION ); printf("C11/OpenMP TARGET STREAM triad: A = B + scalar * C\n"); ////////////////////////////////////////////////////////////////////// /// Read and test input parameters ////////////////////////////////////////////////////////////////////// if (argc < 3) { printf("Usage: <# iterations> <vector length>\n"); return 1; } int iterations = atoi(argv[1]); if (iterations < 1) { printf("ERROR: iterations must be >= 1\n"); return 1; } // length of a the vector size_t length = atol(argv[2]); if (length <= 0) { printf("ERROR: Vector length must be greater than 0\n"); return 1; } int device = (argc > 3) ? atol(argv[3]) : omp_get_default_device(); if ( (device < 0 || omp_get_num_devices() <= device ) && (device != omp_get_default_device()) ) { printf("ERROR: device number %d is not valid.\n", device); return 1; } printf("Number of iterations = %d\n", iterations); printf("Vector length = %zu\n", length); printf("OpenMP Device = %d\n", device); ////////////////////////////////////////////////////////////////////// // Allocate space and perform the computation ////////////////////////////////////////////////////////////////////// double nstream_time = 0.0; int host = omp_get_initial_device(); size_t bytes = length*sizeof(double); double * restrict h_A = omp_target_alloc(bytes, host); double * restrict h_B = omp_target_alloc(bytes, host); double * restrict h_C = omp_target_alloc(bytes, host); double scalar = 3.0; #pragma omp parallel for simd schedule(static) for (size_t i=0; i<length; i++) { h_A[i] = 0.0; h_B[i] = 2.0; h_C[i] = 2.0; } double * restrict d_A = omp_target_alloc(bytes, device); double * restrict d_B = omp_target_alloc(bytes, device); double * restrict d_C = omp_target_alloc(bytes, device); int rc = 0; rc = omp_target_memcpy(d_A, h_A, bytes, 0, 0, device, host); if (rc) { printf("ERROR: omp_target_memcpy(A) returned %d\n", rc); abort(); } rc = omp_target_memcpy(d_B, h_B, bytes, 0, 0, device, host); if (rc) { printf("ERROR: omp_target_memcpy(B) returned %d\n", rc); abort(); } rc = omp_target_memcpy(d_C, h_C, bytes, 0, 0, device, host); if (rc) { printf("ERROR: omp_target_memcpy(C) returned %d\n", rc); abort(); } omp_target_free(h_C, host); omp_target_free(h_B, host); { for (int iter = 0; iter<=iterations; iter++) { if (iter==1) nstream_time = omp_get_wtime(); #pragma omp target teams distribute parallel for simd schedule(static) device(device) is_device_ptr(d_A,d_B,d_C) for (size_t i=0; i<length; i++) { d_A[i] += d_B[i] + scalar * d_C[i]; } } nstream_time = omp_get_wtime() - nstream_time; } rc = omp_target_memcpy(h_A, d_A, bytes, 0, 0, host, device); if (rc) { printf("ERROR: omp_target_memcpy(A) returned %d\n", rc); abort(); } omp_target_free(d_C, device); omp_target_free(d_B, device); omp_target_free(d_A, device); ////////////////////////////////////////////////////////////////////// /// Analyze and output results ////////////////////////////////////////////////////////////////////// double ar = 0.0; double br = 2.0; double cr = 2.0; for (int i=0; i<=iterations; i++) { ar += br + scalar * cr; } ar *= length; double asum = 0.0; #pragma omp parallel for reduction(+:asum) for (size_t i=0; i<length; i++) { asum += fabs(h_A[i]); } omp_target_free(h_A, host); double epsilon=1.e-8; if (fabs(ar-asum)/asum > epsilon) { printf("Failed Validation on output array\n" " Expected checksum: %lf\n" " Observed checksum: %lf\n" "ERROR: solution did not validate\n", ar, asum); return 1; } else { printf("Solution validates\n"); double avgtime = nstream_time/iterations; double nbytes = 4.0 * length * sizeof(double); printf("Rate (MB/s): %lf Avg time (s): %lf\n", 1.e-6*nbytes/avgtime, avgtime); } return 0; }
GB_binop__bget_int64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_int64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_03__bget_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_int64) // C+=b function (dense accum): GB (_Cdense_accumb__bget_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int64) // C=scalar+B GB (_bind1st__bget_int64) // C=scalar+B' GB (_bind1st_tran__bget_int64) // C=A+scalar GB (_bind2nd__bget_int64) // C=A'+scalar GB (_bind2nd_tran__bget_int64) // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = GB_BITGET (aij, bij, int64_t, 64) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_BITGET (x, y, int64_t, 64) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_INT64 || GxB_NO_BGET_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bget_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__bget_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((node)) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_int64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bget_int64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bget_int64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_int64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *Cx = (int64_t *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int64_t bij = Bx [p] ; Cx [p] = GB_BITGET (x, bij, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int64_t *Cx = (int64_t *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_t aij = Ax [p] ; Cx [p] = GB_BITGET (aij, y, int64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITGET (x, aij, int64_t, 64) ; \ } GrB_Info GB (_bind1st_tran__bget_int64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = GB_BITGET (aij, y, int64_t, 64) ; \ } GrB_Info GB (_bind2nd_tran__bget_int64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
helpme.h
// BEGINLICENSE // // This file is part of helPME, which is distributed under the BSD 3-clause license, // as described in the LICENSE file in the top level directory of this project. // // Author: Andrew C. Simmonett // // ENDLICENSE #ifndef _HELPME_HELPME_H_ #define _HELPME_HELPME_H_ #if __cplusplus || DOXYGEN // C++ header #include <algorithm> #include <array> #include <cmath> #include <complex> #include <functional> #include <iostream> #include <memory> #ifdef _OPENMP #include <omp.h> #endif #include <stdexcept> #include <string> #include <tuple> #include <unistd.h> #include <vector> #include "cartesiantransform.h" #include "fftw_wrapper.h" #include "gamma.h" #include "gridsize.h" #include "matrix.h" #include "memory.h" #if HAVE_MPI == 1 #include "mpi_wrapper.h" #else typedef struct ompi_communicator_t *MPI_Comm; #endif #include "powers.h" #include "splines.h" #include "string_utils.h" /*! * \file helpme.h * \brief Contains the C++ implementation of a PME Instance, and related helper classes. */ namespace helpme { /*! * \brief nCartesian computes the total number of Cartesian components of a given angular momentum. * \param L the angular momentum. * \return total number of components up to and including angular momentum L. */ static int nCartesian(int L) { return (L + 1) * (L + 2) * (L + 3) / 6; } /*! * \brief cartAddress computes the address of a term with given quantum numbers in a Cartesian buffer. * \param lx the x quantum number. * \param ly the y quantum number. * \param lz the z quantum number. * \return the address of an {lx, ly, lz} quantity in a buffer that contains all lower angular momentum terms too. */ static int cartAddress(int lx, int ly, int lz) { int l = lx + ly + lz; return l * (l + 1) * (l + 2) / 6 + lz * (l * 2 - lz + 3) / 2 + ly; } // This is used to define function pointers in the constructor, and makes it easy to add new kernels. #define ENABLE_KERNEL_WITH_INVERSE_R_EXPONENT_OF(n) \ case n: \ convolveEVFxn_ = &convolveEVImpl<n>; \ cacheInfluenceFunctionFxn_ = &cacheInfluenceFunctionImpl<n>; \ slfEFxn_ = &slfEImpl<n>; \ dirEFxn_ = &dirEImpl<n>; \ adjEFxn_ = &adjEImpl<n>; \ dirEFFxn_ = &dirEFImpl<n>; \ adjEFFxn_ = &adjEFImpl<n>; \ break; /*! * \class splineCacheEntry * \brief A placeholder to encapsulate information about a given atom's splines */ template <typename Real> struct SplineCacheEntry { BSpline<Real> aSpline, bSpline, cSpline; int absoluteAtomNumber; SplineCacheEntry(int order, int derivativeLevel) : aSpline(0, 0, order, derivativeLevel), bSpline(0, 0, order, derivativeLevel), cSpline(0, 0, order, derivativeLevel), absoluteAtomNumber(-1) {} }; /*! * \class PMEInstance * \brief A class to encapsulate information related to a particle mesh Ewald calculation. * * By storing information related to a single PME calculation in this way, we allow multiple * instances to be created in calculations requiring multiple PMEs, e.g. for computing both * electrostatic and attractive dispersion terms using PME to handle long-range interactions. * \tparam Real the floating point type to use for arithmetic. */ template <typename Real> class PMEInstance { using GridIterator = std::vector<std::vector<std::pair<short, short>>>; using Complex = std::complex<Real>; using Spline = BSpline<Real>; using RealMat = Matrix<Real>; using RealVec = helpme::vector<Real>; public: /*! * \brief The different conventions for orienting a lattice constructed from input parameters. */ enum class LatticeType : int { XAligned = 0, ShapeMatrix = 1 }; /*! * \brief The different conventions for numbering nodes. */ enum class NodeOrder : int { ZYX = 0 }; protected: /// The FFT grid dimensions in the {A,B,C} grid dimensions. int dimA_, dimB_, dimC_; /// The full A dimension after real->complex transformation. int complexDimA_; /// The locally owned A dimension after real->complex transformation. int myComplexDimA_; /// The order of the cardinal B-Spline used for interpolation. int splineOrder_; /// The actual number of threads per MPI instance, and the number requested previously. int nThreads_, requestedNumberOfThreads_; /// The exponent of the (inverse) interatomic distance used in this kernel. int rPower_; /// The scale factor to apply to all energies and derivatives. Real scaleFactor_; /// The attenuation parameter, whose units should be the inverse of those used to specify coordinates. Real kappa_; /// The lattice vectors. RealMat boxVecs_; /// The reciprocal lattice vectors. RealMat recVecs_; /// The scaled reciprocal lattice vectors, for transforming forces from scaled fractional coordinates. RealMat scaledRecVecs_; /// An iterator over angular momentum components. std::vector<std::array<short, 3>> angMomIterator_; /// The number of permutations of each multipole component. RealVec permutations_; /// From a given starting point on the {A,B,C} edge of the grid, lists all points to be handled, correctly wrapping /// around the end. GridIterator gridIteratorA_, gridIteratorB_, gridIteratorC_; /// The (inverse) bspline moduli to normalize the spreading / probing steps; these are folded into the convolution. RealVec splineModA_, splineModB_, splineModC_; /// The cached influence function involved in the convolution. RealVec cachedInfluenceFunction_; /// A function pointer to call the approprate function to implement convolution with virial, templated to /// the rPower value. std::function<Real(int, int, int, int, int, int, int, Real, Complex *, const RealMat &, Real, Real, const Real *, const Real *, const Real *, RealMat &, int)> convolveEVFxn_; /// A function pointer to call the approprate function to implement cacheing of the influence function that appears // in the convolution, templated to the rPower value. std::function<void(int, int, int, int, int, int, int, Real, RealVec &, const RealMat &, Real, Real, const Real *, const Real *, const Real *, int)> cacheInfluenceFunctionFxn_; /// A function pointer to call the approprate function to compute self energy, templated to the rPower value. std::function<Real(int, const RealMat &, Real, Real)> slfEFxn_; /// A function pointer to call the approprate function to compute the direct energy, templated to the rPower value. std::function<Real(Real, Real)> dirEFxn_; /// A function pointer to call the approprate function to compute the adjusted energy, templated to the rPower /// value. std::function<Real(Real, Real)> adjEFxn_; /// A function pointer to call the approprate function to compute the direct energy and force, templated to the /// rPower value. std::function<std::tuple<Real, Real>(Real, Real, Real)> dirEFFxn_; /// A function pointer to call the approprate function to compute the adjusted energy and force, templated to the /// rPower value. std::function<std::tuple<Real, Real>(Real, Real, Real)> adjEFFxn_; #if HAVE_MPI == 1 /// The communicator object that handles interactions with MPI. std::unique_ptr<MPIWrapper<Real>> mpiCommunicator_; /// The communicator object that handles interactions with MPI along this nodes {A,B,C} pencils. std::unique_ptr<MPIWrapper<Real>> mpiCommunicatorA_, mpiCommunicatorB_, mpiCommunicatorC_; #endif /// The number of nodes in the {A,B,C} dimensions. int numNodesA_, numNodesB_, numNodesC_; /// The rank of this node along the {A,B,C} dimensions. int rankA_, rankB_, rankC_; /// The first grid point that this node is responsible for in the {A,B,C} dimensions. int firstA_, firstB_, firstC_; /// The grid point beyond the last point that this this node is responsible for in the {A,B,C} dimensions. int lastA_, lastB_, lastC_; /// The {X,Y,Z} dimensions of the locally owned chunk of the grid. int myDimA_, myDimB_, myDimC_; /// The subsets of a given dimension to be processed when doing a transform along another dimension. int subsetOfCAlongA_, subsetOfCAlongB_, subsetOfBAlongC_; /// The size of a cache line, in units of the size of the Real type, to allow better memory allocation policies. Real cacheLineSizeInReals_; /// The current unit cell parameters. Real cellA_, cellB_, cellC_, cellAlpha_, cellBeta_, cellGamma_; /// Whether the unit cell parameters have been changed, invalidating cached gF quantities. bool unitCellHasChanged_; /// Whether the kappa has been changed, invalidating kappa-dependent quantities. bool kappaHasChanged_; /// Whether any of the grid dimensions have changed. bool gridDimensionHasChanged_; /// Whether the spline order has changed. bool splineOrderHasChanged_; /// Whether the scale factor has changed. bool scaleFactorHasChanged_; /// Whether the power of R has changed. bool rPowerHasChanged_; /// Whether the parallel node setup has changed in any way. bool numNodesHasChanged_; /// The type of alignment scheme used for the lattice vectors. LatticeType latticeType_; /// Communication buffers for MPI parallelism. helpme::vector<Complex> workSpace1_, workSpace2_; /// FFTW wrappers to help with transformations in the {A,B,C} dimensions. FFTWWrapper<Real> fftHelperA_, fftHelperB_, fftHelperC_; /// The list of atoms, and their fractional coordinates, that will contribute to this node. std::vector<std::tuple<int, Real, Real, Real>> atomList_; /// The cached list of splines, which is stored as a member to make it persistent. std::vector<SplineCacheEntry<Real>> splineCache_; /*! * \brief A simple helper to compute factorials. * \param n the number whose factorial is to be taken. * \return n! */ unsigned int factorial(unsigned int n) { unsigned int ret = 1; for (unsigned int i = 1; i <= n; ++i) ret *= i; return ret; } /*! * \brief makeGridIterator makes an iterator over the spline values that contribute to this node's grid * in a given Cartesian dimension. The iterator is of the form (grid point, spline index) and is * sorted by increasing grid point, for cache efficiency. * \param dimension the dimension of the grid in the Cartesian dimension of interest. * \param first the first grid point in the Cartesian dimension to be handled by this node. * \param last the element past the last grid point in the Cartesian dimension to be handled by this node. * \return the vector of spline iterators for each starting grid point. */ GridIterator makeGridIterator(int dimension, int first, int last) const { GridIterator gridIterator; for (int gridStart = 0; gridStart < dimension; ++gridStart) { std::vector<std::pair<short, short>> splineIterator(splineOrder_); splineIterator.clear(); for (int splineIndex = 0; splineIndex < splineOrder_; ++splineIndex) { int gridPoint = (splineIndex + gridStart) % dimension; if (gridPoint >= first && gridPoint < last) splineIterator.push_back(std::make_pair(gridPoint - first, splineIndex)); } splineIterator.shrink_to_fit(); std::sort(splineIterator.begin(), splineIterator.end()); gridIterator.push_back(splineIterator); } gridIterator.shrink_to_fit(); return gridIterator; } /*! Make sure that the iterator over AM components is up to date. * \param angMom the angular momentum required for the iterator over multipole components. */ void updateAngMomIterator(int parameterAngMom) { auto L = parameterAngMom; size_t expectedNTerms = nCartesian(L); if (angMomIterator_.size() >= expectedNTerms) return; angMomIterator_.resize(expectedNTerms); permutations_.resize(expectedNTerms); for (short l = 0, count = 0; l <= L; ++l) { for (short lz = 0; lz <= l; ++lz) { for (short ly = 0; ly <= l - lz; ++ly) { short lx = l - ly - lz; angMomIterator_[count] = {{static_cast<short>(lx), static_cast<short>(ly), static_cast<short>(lz)}}; permutations_[count] = (Real)factorial(l) / (factorial(lx) * factorial(ly) * factorial(lz)); ++count; } } } } /*! * \brief updateInfluenceFunction builds the gF array cache, if the lattice vector has changed since the last * build of it. If the cell is unchanged, this does nothing. */ void updateInfluenceFunction() { if (unitCellHasChanged_ || kappaHasChanged_ || gridDimensionHasChanged_ || splineOrderHasChanged_ || scaleFactorHasChanged_ || numNodesHasChanged_) { cacheInfluenceFunctionFxn_(dimA_, dimB_, dimC_, myComplexDimA_, myDimB_ / numNodesC_, rankA_ * myComplexDimA_, rankB_ * myDimB_ + rankC_ * myDimB_ / numNodesC_, scaleFactor_, cachedInfluenceFunction_, recVecs_, cellVolume(), kappa_, &splineModA_[0], &splineModB_[0], &splineModC_[0], nThreads_); } } /*! * \brief filterAtomsAndBuildSplineCache builds a list of BSplines for only the atoms to be handled by this node. * \param splineDerivativeLevel the derivative level (parameter angular momentum + energy derivative level) of the * BSplines. \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. */ void filterAtomsAndBuildSplineCache(int splineDerivativeLevel, const RealMat &coords) { assertInitialized(); atomList_.clear(); size_t nAtoms = coords.nRows(); for (int atom = 0; atom < nAtoms; ++atom) { const Real *atomCoords = coords[atom]; constexpr float EPS = 1e-6; Real aCoord = atomCoords[0] * recVecs_(0, 0) + atomCoords[1] * recVecs_(1, 0) + atomCoords[2] * recVecs_(2, 0) - EPS; Real bCoord = atomCoords[0] * recVecs_(0, 1) + atomCoords[1] * recVecs_(1, 1) + atomCoords[2] * recVecs_(2, 1) - EPS; Real cCoord = atomCoords[0] * recVecs_(0, 2) + atomCoords[1] * recVecs_(1, 2) + atomCoords[2] * recVecs_(2, 2) - EPS; // Make sure the fractional coordinates fall in the range 0 <= s < 1 aCoord -= floor(aCoord); bCoord -= floor(bCoord); cCoord -= floor(cCoord); short aStartingGridPoint = dimA_ * aCoord; short bStartingGridPoint = dimB_ * bCoord; short cStartingGridPoint = dimC_ * cCoord; const auto &aGridIterator = gridIteratorA_[aStartingGridPoint]; const auto &bGridIterator = gridIteratorB_[bStartingGridPoint]; const auto &cGridIterator = gridIteratorC_[cStartingGridPoint]; if (aGridIterator.size() && bGridIterator.size() && cGridIterator.size()) atomList_.emplace_back(atom, aCoord, bCoord, cCoord); } // Now we know how many atoms we loop over the dense list, redefining nAtoms accordingly. // The first stage above is to get the number of atoms, so we can avoid calling push_back // and thus avoid the many memory allocations. If the cache is too small, grow it by a // certain scale factor to try and minimize allocations in a not-too-wasteful manner. nAtoms = atomList_.size(); if (splineCache_.size() < nAtoms) { size_t newSize = static_cast<size_t>(1.2 * nAtoms); for (int atom = splineCache_.size(); atom < newSize; ++atom) splineCache_.emplace_back(splineOrder_, splineDerivativeLevel); } for (int atomListNum = 0; atomListNum < nAtoms; ++atomListNum) { const auto &entry = atomList_[atomListNum]; const int absoluteAtomNumber = std::get<0>(entry); const Real aCoord = std::get<1>(entry); const Real bCoord = std::get<2>(entry); const Real cCoord = std::get<3>(entry); short aStartingGridPoint = dimA_ * aCoord; short bStartingGridPoint = dimB_ * bCoord; short cStartingGridPoint = dimC_ * cCoord; auto &atomSplines = splineCache_[atomListNum]; atomSplines.absoluteAtomNumber = absoluteAtomNumber; atomSplines.aSpline.update(aStartingGridPoint, dimA_ * aCoord - aStartingGridPoint, splineOrder_, splineDerivativeLevel); atomSplines.bSpline.update(bStartingGridPoint, dimB_ * bCoord - bStartingGridPoint, splineOrder_, splineDerivativeLevel); atomSplines.cSpline.update(cStartingGridPoint, dimC_ * cCoord - cStartingGridPoint, splineOrder_, splineDerivativeLevel); } } /*! * \brief Spreads parameters onto the grid for a single atom * \param atom the absolute atom number. * \param realGrid pointer to the array containing the grid in CBA order * \param nComponents the number of angular momentum components in the parameters. * \param nForceComponents the number of angular momentum components in the parameters with one extra * level of angular momentum to permit evaluation of forces. * \param splineA the BSpline object for the A direction. * \param splineB the BSpline object for the B direction. * \param splineC the BSpline object for the C direction. * \param parameters the list of parameters associated with each atom (charges, C6 coefficients, multipoles, * etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = * (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode */ void spreadParametersImpl(const int &atom, Real *realGrid, const int &nComponents, const Spline &splineA, const Spline &splineB, const Spline &splineC, const RealMat &parameters) { const auto &aGridIterator = gridIteratorA_[splineA.startingGridPoint()]; const auto &bGridIterator = gridIteratorB_[splineB.startingGridPoint()]; const auto &cGridIterator = gridIteratorC_[splineC.startingGridPoint()]; int numPointsA = static_cast<int>(aGridIterator.size()); int numPointsB = static_cast<int>(bGridIterator.size()); int numPointsC = static_cast<int>(cGridIterator.size()); const auto *iteratorDataA = aGridIterator.data(); const auto *iteratorDataB = bGridIterator.data(); const auto *iteratorDataC = cGridIterator.data(); for (int component = 0; component < nComponents; ++component) { const auto &quanta = angMomIterator_[component]; Real param = parameters(atom, component); const Real *splineValsA = splineA[quanta[0]]; const Real *splineValsB = splineB[quanta[1]]; const Real *splineValsC = splineC[quanta[2]]; for (int pointC = 0; pointC < numPointsC; ++pointC) { const auto &cPoint = iteratorDataC[pointC]; Real cValP = param * splineValsC[cPoint.second]; for (int pointB = 0; pointB < numPointsB; ++pointB) { const auto &bPoint = iteratorDataB[pointB]; Real cbValP = cValP * splineValsB[bPoint.second]; Real *cbRow = realGrid + cPoint.first * myDimB_ * myDimA_ + bPoint.first * myDimA_; for (int pointA = 0; pointA < numPointsA; ++pointA) { const auto &aPoint = iteratorDataA[pointA]; cbRow[aPoint.first] += cbValP * splineValsA[aPoint.second]; } } } } } /*! * \brief Probes the grid and computes the force for a single atom, specialized for zero parameter angular momentum. * \param potentialGrid pointer to the array containing the potential, in ZYX order. * \param splineA the BSpline object for the A direction. * \param splineB the BSpline object for the B direction. * \param splineC the BSpline object for the C direction. * \param parameter the list of parameter associated with the given atom. * \param forces a 3 vector of the forces for this atom, ordered in memory as {Fx, Fy, Fz}. */ void probeGridImpl(const Real *potentialGrid, const Spline &splineA, const Spline &splineB, const Spline &splineC, const Real &parameter, Real *forces) const { const auto &aGridIterator = gridIteratorA_[splineA.startingGridPoint()]; const auto &bGridIterator = gridIteratorB_[splineB.startingGridPoint()]; const auto &cGridIterator = gridIteratorC_[splineC.startingGridPoint()]; // We unpack the vector to raw pointers, as profiling shows that using range based for loops over vectors // causes a signficant penalty in the innermost loop, primarily due to checking the loop stop condition. int numPointsA = static_cast<int>(aGridIterator.size()); int numPointsB = static_cast<int>(bGridIterator.size()); int numPointsC = static_cast<int>(cGridIterator.size()); const auto *iteratorDataA = aGridIterator.data(); const auto *iteratorDataB = bGridIterator.data(); const auto *iteratorDataC = cGridIterator.data(); const Real *splineStartA0 = splineA[0]; const Real *splineStartB0 = splineB[0]; const Real *splineStartC0 = splineC[0]; const Real *splineStartA1 = splineStartA0 + splineOrder_; const Real *splineStartB1 = splineStartB0 + splineOrder_; const Real *splineStartC1 = splineStartC0 + splineOrder_; Real Ex = 0, Ey = 0, Ez = 0; for (int pointC = 0; pointC < numPointsC; ++pointC) { const auto &cPoint = iteratorDataC[pointC]; const Real &splineC0 = splineStartC0[cPoint.second]; const Real &splineC1 = splineStartC1[cPoint.second]; for (int pointB = 0; pointB < numPointsB; ++pointB) { const auto &bPoint = iteratorDataB[pointB]; const Real &splineB0 = splineStartB0[bPoint.second]; const Real &splineB1 = splineStartB1[bPoint.second]; const Real *cbRow = potentialGrid + cPoint.first * myDimA_ * myDimB_ + bPoint.first * myDimA_; for (int pointA = 0; pointA < numPointsA; ++pointA) { const auto &aPoint = iteratorDataA[pointA]; const Real &splineA0 = splineStartA0[aPoint.second]; const Real &splineA1 = splineStartA1[aPoint.second]; const Real &gridVal = cbRow[aPoint.first]; Ey += gridVal * splineA0 * splineB1 * splineC0; Ez += gridVal * splineA0 * splineB0 * splineC1; Ex += gridVal * splineA1 * splineB0 * splineC0; } } } forces[0] -= parameter * (scaledRecVecs_[0][0] * Ex + scaledRecVecs_[0][1] * Ey + scaledRecVecs_[0][2] * Ez); forces[1] -= parameter * (scaledRecVecs_[1][0] * Ex + scaledRecVecs_[1][1] * Ey + scaledRecVecs_[1][2] * Ez); forces[2] -= parameter * (scaledRecVecs_[2][0] * Ex + scaledRecVecs_[2][1] * Ey + scaledRecVecs_[2][2] * Ez); } /*! * \brief Probes the grid and computes the force for a single atom, for arbitrary parameter angular momentum. * \param potentialGrid pointer to the array containing the potential, in ZYX order. * \param nPotentialComponents the number of components in the potential and its derivatives with one extra * level of angular momentum to permit evaluation of forces. * \param splineA the BSpline object for the A direction. * \param splineB the BSpline object for the B direction. * \param splineC the BSpline object for the C direction. * \param phiPtr a scratch array of length nPotentialComponents, to store the fractional potential. * N.B. Make sure that updateAngMomIterator() has been called first with the appropriate derivative * level for the requested potential derivatives. */ void probeGridImpl(const Real *potentialGrid, const int &nPotentialComponents, const Spline &splineA, const Spline &splineB, const Spline &splineC, Real *phiPtr) { const auto &aGridIterator = gridIteratorA_[splineA.startingGridPoint()]; const auto &bGridIterator = gridIteratorB_[splineB.startingGridPoint()]; const auto &cGridIterator = gridIteratorC_[splineC.startingGridPoint()]; const Real *splineStartA = splineA[0]; const Real *splineStartB = splineB[0]; const Real *splineStartC = splineC[0]; for (const auto &cPoint : cGridIterator) { for (const auto &bPoint : bGridIterator) { const Real *cbRow = potentialGrid + cPoint.first * myDimA_ * myDimB_ + bPoint.first * myDimA_; for (const auto &aPoint : aGridIterator) { Real gridVal = cbRow[aPoint.first]; for (int component = 0; component < nPotentialComponents; ++component) { const auto &quanta = angMomIterator_[component]; const Real *splineValsA = splineStartA + quanta[0] * splineOrder_; const Real *splineValsB = splineStartB + quanta[1] * splineOrder_; const Real *splineValsC = splineStartC + quanta[2] * splineOrder_; phiPtr[component] += gridVal * splineValsA[aPoint.second] * splineValsB[bPoint.second] * splineValsC[cPoint.second]; } } } } } /*! * \brief Probes the grid and computes the force for a single atom, for arbitrary parameter angular momentum. * \param atom the absolute atom number. * \param potentialGrid pointer to the array containing the potential, in ZYX order. * \param nComponents the number of angular momentum components in the parameters. * \param nForceComponents the number of angular momentum components in the parameters with one extra * level of angular momentum to permit evaluation of forces. * \param splineA the BSpline object for the A direction. * \param splineB the BSpline object for the B direction. * \param splineC the BSpline object for the C direction. * \param phiPtr a scratch array of length nForceComponents, to store the fractional potential. * \param parameters the list of parameters associated with each atom (charges, C6 coefficients, multipoles, * etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = * (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. */ void probeGridImpl(const int &atom, const Real *potentialGrid, const int &nComponents, const int &nForceComponents, const Spline &splineA, const Spline &splineB, const Spline &splineC, Real *phiPtr, const RealMat &parameters, Real *forces) { std::fill(phiPtr, phiPtr + nForceComponents, 0); probeGridImpl(potentialGrid, nForceComponents, splineA, splineB, splineC, phiPtr); Real fracForce[3] = {0, 0, 0}; for (int component = 0; component < nComponents; ++component) { Real param = parameters(atom, component); const auto &quanta = angMomIterator_[component]; short lx = quanta[0]; short ly = quanta[1]; short lz = quanta[2]; fracForce[0] -= param * phiPtr[cartAddress(lx + 1, ly, lz)]; fracForce[1] -= param * phiPtr[cartAddress(lx, ly + 1, lz)]; fracForce[2] -= param * phiPtr[cartAddress(lx, ly, lz + 1)]; } forces[0] += scaledRecVecs_[0][0] * fracForce[0] + scaledRecVecs_[0][1] * fracForce[1] + scaledRecVecs_[0][2] * fracForce[2]; forces[1] += scaledRecVecs_[1][0] * fracForce[0] + scaledRecVecs_[1][1] * fracForce[1] + scaledRecVecs_[1][2] * fracForce[2]; forces[2] += scaledRecVecs_[2][0] * fracForce[0] + scaledRecVecs_[2][1] * fracForce[1] + scaledRecVecs_[2][2] * fracForce[2]; } /*! * \brief assertInitialized makes sure that setup() has been called before running any calculations. */ void assertInitialized() const { if (!rPower_) throw std::runtime_error( "Either setup(...) or setup_parallel(...) must be called before computing anything."); } /*! * \brief makeBSplines construct the {x,y,z} B-Splines. * \param atomCoords a 3-vector containing the atom's coordinates. * \param derivativeLevel level of derivative needed for the splines. * \return a 3-tuple containing the {x,y,z} B-splines. */ std::tuple<Spline, Spline, Spline> makeBSplines(const Real *atomCoords, short derivativeLevel) const { // Subtract a tiny amount to make sure we're not exactly on the rightmost (excluded) // grid point. The calculation is translationally invariant, so this is valid. constexpr float EPS = 1e-6f; Real aCoord = atomCoords[0] * recVecs_(0, 0) + atomCoords[1] * recVecs_(1, 0) + atomCoords[2] * recVecs_(2, 0) - EPS; Real bCoord = atomCoords[0] * recVecs_(0, 1) + atomCoords[1] * recVecs_(1, 1) + atomCoords[2] * recVecs_(2, 1) - EPS; Real cCoord = atomCoords[0] * recVecs_(0, 2) + atomCoords[1] * recVecs_(1, 2) + atomCoords[2] * recVecs_(2, 2) - EPS; // Make sure the fractional coordinates fall in the range 0 <= s < 1 aCoord -= floor(aCoord); bCoord -= floor(bCoord); cCoord -= floor(cCoord); short aStartingGridPoint = dimA_ * aCoord; short bStartingGridPoint = dimB_ * bCoord; short cStartingGridPoint = dimC_ * cCoord; Real aDistanceFromGridPoint = dimA_ * aCoord - aStartingGridPoint; Real bDistanceFromGridPoint = dimB_ * bCoord - bStartingGridPoint; Real cDistanceFromGridPoint = dimC_ * cCoord - cStartingGridPoint; return std::make_tuple(Spline(aStartingGridPoint, aDistanceFromGridPoint, splineOrder_, derivativeLevel), Spline(bStartingGridPoint, bDistanceFromGridPoint, splineOrder_, derivativeLevel), Spline(cStartingGridPoint, cDistanceFromGridPoint, splineOrder_, derivativeLevel)); } /*! * \brief sanityChecks just makes sure that inputs have consistent dimensions, and that prerequisites are * initialized. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). * \param parameters the input parameters. * \param coordinates the input coordinates. */ void sanityChecks(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { assertInitialized(); if (parameters.nRows() == 0) throw std::runtime_error("Parameters have not been set yet! Call setParameters(...) before runPME(...);"); if (coordinates.nRows() == 0) throw std::runtime_error( "Coordinates have not been set yet! Call setCoordinates(...) before runPME(...);"); if (boxVecs_.isNearZero()) throw std::runtime_error( "Lattice vectors have not been set yet! Call setLatticeVectors(...) before runPME(...);"); if (coordinates.nRows() != parameters.nRows()) throw std::runtime_error( "Inconsistent number of coordinates and parameters; there should be nAtoms of each."); if (parameters.nCols() != nCartesian(parameterAngMom)) throw std::runtime_error( "Mismatch in the number of parameters provided and the parameter angular momentum"); } /*! * \brief convolveEVImpl performs the reciprocal space convolution, returning the energy. We opt to not cache * this the same way as the non-virial version because it's safe to assume that if the virial is requested * the box is likely to change, which renders the cache useless. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param nx the grid dimension in the x direction. * \param ny the grid dimension in the y direction. * \param nz the grid dimension in the z direction. * \param myNx the subset of the grid in the x direction to be handled by this node. * \param myNy the subset of the grid in the y direction to be handled by this node. * \param startX the starting grid point handled by this node in the X direction. * \param startY the starting grid point handled by this node in the Y direction. * \param scaleFactor a scale factor to be applied to all computed energies and derivatives thereof (e.g. the * 1 / [4 pi epslion0] for Coulomb calculations). * \param gridPtr the Fourier space grid, with ordering YXZ. * \param boxInv the reciprocal lattice vectors. * \param volume the volume of the unit cell. * \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param xMods the Fourier space norms of the x B-Splines. * \param yMods the Fourier space norms of the y B-Splines. * \param zMods the Fourier space norms of the z B-Splines. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \param nThreads the number of OpenMP threads to use. * \return the reciprocal space energy. */ template <int rPower> static Real convolveEVImpl(int nx, int ny, int nz, int myNx, int myNy, int startX, int startY, Real scaleFactor, Complex *gridPtr, const RealMat &boxInv, Real volume, Real kappa, const Real *xMods, const Real *yMods, const Real *zMods, RealMat &virial, int nThreads) { Real energy = 0; bool nodeZero = startX == 0 && startY == 0; if (rPower > 3 && nodeZero) { // Kernels with rPower>3 are absolutely convergent and should have the m=0 term present. // To compute it we need sum_ij c(i)c(j), which can be obtained from the structure factor norm. Real prefac = 2 * scaleFactor * M_PI * sqrtPi * pow(kappa, rPower - 3) / ((rPower - 3) * gammaComputer<Real, rPower>::value * volume); energy += prefac * std::norm(gridPtr[0]); } // Ensure the m=0 term convolution product is zeroed for the backtransform; it's been accounted for above. if (nodeZero) gridPtr[0] = Complex(0, 0); std::vector<Real> xMVals(myNx), yMVals(myNy), zMVals(nz); // Iterators to conveniently map {X,Y,Z} grid location to m_{X,Y,Z} value, where -1/2 << m/dim < 1/2. for (int kx = 0; kx < myNx; ++kx) xMVals[kx] = startX + (kx + startX >= (nx + 1) / 2 ? kx - nx : kx); for (int ky = 0; ky < myNy; ++ky) yMVals[ky] = startY + (ky + startY >= (ny + 1) / 2 ? ky - ny : ky); for (int kz = 0; kz < nz; ++kz) zMVals[kz] = kz >= (nz + 1) / 2 ? kz - nz : kz; Real bPrefac = M_PI * M_PI / (kappa * kappa); Real volPrefac = scaleFactor * pow(M_PI, rPower - 1) / (sqrtPi * gammaComputer<Real, rPower>::value * volume); int halfNx = nx / 2 + 1; size_t nxz = myNx * nz; Real Vxx = 0, Vxy = 0, Vyy = 0, Vxz = 0, Vyz = 0, Vzz = 0; const Real *boxPtr = boxInv[0]; const Real *xMPtr = xMVals.data(); const Real *yMPtr = yMVals.data(); const Real *zMPtr = zMVals.data(); size_t nyxz = myNy * nxz; // Exclude m=0 cell. int start = (nodeZero ? 1 : 0); // Writing the three nested loops in one allows for better load balancing in parallel. #pragma omp parallel for reduction(+ : energy, Vxx, Vxy, Vyy, Vxz, Vyz, Vzz) num_threads(nThreads) for (size_t yxz = start; yxz < nyxz; ++yxz) { size_t xz = yxz % nxz; short ky = yxz / nxz; short kx = xz / nz; short kz = xz % nz; // We only loop over the first nx/2+1 x values; this // accounts for the "missing" complex conjugate values. Real permPrefac = kx + startX != 0 && kx + startX != halfNx - 1 ? 2 : 1; const Real &mx = xMPtr[kx]; const Real &my = yMPtr[ky]; const Real &mz = zMPtr[kz]; Real mVecX = boxPtr[0] * mx + boxPtr[1] * my + boxPtr[2] * mz; Real mVecY = boxPtr[3] * mx + boxPtr[4] * my + boxPtr[5] * mz; Real mVecZ = boxPtr[6] * mx + boxPtr[7] * my + boxPtr[8] * mz; Real mNormSq = mVecX * mVecX + mVecY * mVecY + mVecZ * mVecZ; Real mTerm = raiseNormToIntegerPower<Real, rPower - 3>::compute(mNormSq); Real bSquared = bPrefac * mNormSq; auto gammas = incompleteGammaVirialComputer<Real, 3 - rPower>::compute(bSquared); Real eGamma = std::get<0>(gammas); Real vGamma = std::get<1>(gammas); Complex &gridVal = gridPtr[yxz]; Real structFacNorm = std::norm(gridVal); Real totalPrefac = volPrefac * mTerm * yMods[ky + startY] * xMods[kx + startX] * zMods[kz]; Real influenceFunction = totalPrefac * eGamma; gridVal *= influenceFunction; Real eTerm = permPrefac * influenceFunction * structFacNorm; Real vTerm = permPrefac * vGamma * totalPrefac / mNormSq * structFacNorm; energy += eTerm; Vxx += vTerm * mVecX * mVecX; Vxy += vTerm * mVecX * mVecY; Vyy += vTerm * mVecY * mVecY; Vxz += vTerm * mVecX * mVecZ; Vyz += vTerm * mVecY * mVecZ; Vzz += vTerm * mVecZ * mVecZ; } energy /= 2; virial[0][0] -= Vxx - energy; virial[0][1] -= Vxy; virial[0][2] -= Vyy - energy; virial[0][3] -= Vxz; virial[0][4] -= Vyz; virial[0][5] -= Vzz - energy; return energy; } /*! * \brief cacheInfluenceFunctionImpl computes the influence function used in convolution, for later use. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param nx the grid dimension in the x direction. * \param ny the grid dimension in the y direction. * \param nz the grid dimension in the z direction. * \param myNx the subset of the grid in the x direction to be handled by this node. * \param myNy the subset of the grid in the y direction to be handled by this node. * \param startX the starting grid point handled by this node in the X direction. * \param startY the starting grid point handled by this node in the Y direction. * \param scaleFactor a scale factor to be applied to all computed energies and derivatives thereof (e.g. the * 1 / [4 pi epslion0] for Coulomb calculations). * \param gridPtr the Fourier space grid, with ordering YXZ. * \param boxInv the reciprocal lattice vectors. * \param volume the volume of the unit cell. * \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param xMods the Fourier space norms of the x B-Splines. * \param yMods the Fourier space norms of the y B-Splines. * \param zMods the Fourier space norms of the z B-Splines. * This vector is incremented, not assigned. * \param nThreads the number of OpenMP threads to use. * \return the energy for the m=0 term. */ template <int rPower> static void cacheInfluenceFunctionImpl(int nx, int ny, int nz, int myNx, int myNy, int startX, int startY, Real scaleFactor, RealVec &influenceFunction, const RealMat &boxInv, Real volume, Real kappa, const Real *xMods, const Real *yMods, const Real *zMods, int nThreads) { bool nodeZero = startX == 0 && startY == 0; size_t nxz = myNx * nz; size_t nyxz = myNy * nxz; influenceFunction.resize(nyxz); Real *gridPtr = influenceFunction.data(); if (nodeZero) gridPtr[0] = 0; std::vector<Real> xMVals(myNx), yMVals(myNy), zMVals(nz); // Iterators to conveniently map {X,Y,Z} grid location to m_{X,Y,Z} value, where -1/2 << m/dim < 1/2. for (int kx = 0; kx < myNx; ++kx) xMVals[kx] = startX + (kx + startX >= (nx + 1) / 2 ? kx - nx : kx); for (int ky = 0; ky < myNy; ++ky) yMVals[ky] = startY + (ky + startY >= (ny + 1) / 2 ? ky - ny : ky); for (int kz = 0; kz < nz; ++kz) zMVals[kz] = kz >= (nz + 1) / 2 ? kz - nz : kz; Real bPrefac = M_PI * M_PI / (kappa * kappa); Real volPrefac = scaleFactor * pow(M_PI, rPower - 1) / (sqrtPi * gammaComputer<Real, rPower>::value * volume); const Real *boxPtr = boxInv[0]; // Exclude m=0 cell. int start = (nodeZero ? 1 : 0); // Writing the three nested loops in one allows for better load balancing in parallel. #pragma omp parallel for num_threads(nThreads) for (size_t yxz = start; yxz < nyxz; ++yxz) { size_t xz = yxz % nxz; short ky = yxz / nxz; short kx = xz / nz; short kz = xz % nz; Real mx = (Real)xMVals[kx]; Real my = (Real)yMVals[ky]; Real mz = (Real)zMVals[kz]; Real mVecX = boxPtr[0] * mx + boxPtr[1] * my + boxPtr[2] * mz; Real mVecY = boxPtr[3] * mx + boxPtr[4] * my + boxPtr[5] * mz; Real mVecZ = boxPtr[6] * mx + boxPtr[7] * my + boxPtr[8] * mz; Real mNormSq = mVecX * mVecX + mVecY * mVecY + mVecZ * mVecZ; Real mTerm = raiseNormToIntegerPower<Real, rPower - 3>::compute(mNormSq); Real bSquared = bPrefac * mNormSq; Real incompleteGammaTerm = incompleteGammaComputer<Real, 3 - rPower>::compute(bSquared); gridPtr[yxz] = volPrefac * incompleteGammaTerm * mTerm * yMods[ky + startY] * xMods[kx + startX] * zMods[kz]; } } /*! * \brief dirEImpl computes the kernel for the direct energy for a pair. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param rSquared the square of the internuclear distance * \param kappaSquared the square of attenuation parameter in units inverse of those used to specify coordinates. * \return the energy kernel. */ template <int rPower> inline static Real dirEImpl(Real rSquared, Real kappaSquared) { Real denominator = raiseNormToIntegerPower<Real, rPower>::compute(rSquared); Real gammaTerm = incompleteGammaComputer<Real, rPower>::compute(rSquared * kappaSquared) / gammaComputer<Real, rPower>::value; return gammaTerm / denominator; } /*! * \brief dirEFImpl computes the kernels for the direct energy and force for a pair. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param rSquared the square of the internuclear distance * \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param kappaSquared the square of attenuation parameter in units inverse of those used to specify coordinates. * \return a tuple containing the energy and force kernels, respectively. */ template <int rPower> inline static std::tuple<Real, Real> dirEFImpl(Real rSquared, Real kappa, Real kappaSquared) { Real rInv = 1 / rSquared; Real kappaToRPower = kappa; for (int i = 1; i < rPower; ++i) kappaToRPower *= kappa; Real denominator = raiseNormToIntegerPower<Real, rPower>::compute(rSquared); Real gammaTerm = incompleteGammaComputer<Real, rPower>::compute(rSquared * kappaSquared) / gammaComputer<Real, rPower>::value; Real eKernel = gammaTerm / denominator; Real fKernel = -rPower * eKernel * rInv - 2 * rInv * exp(-kappaSquared * rSquared) * kappaToRPower / gammaComputer<Real, rPower>::value; return std::make_tuple(eKernel, fKernel); } /*! * \brief adjEImpl computes the kernel for the adjusted energy for a pair. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param rSquared the square of the internuclear distance * \param kappaSquared the square of attenuation parameter in units inverse of those used to specify coordinates. * \return the energy kernel. */ template <int rPower> inline static Real adjEImpl(Real rSquared, Real kappaSquared) { Real denominator = raiseNormToIntegerPower<Real, rPower>::compute(rSquared); Real gammaTerm = incompleteGammaComputer<Real, rPower>::compute(rSquared * kappaSquared) / gammaComputer<Real, rPower>::value; return (gammaTerm - 1) / denominator; } /*! * \brief adjEFImpl computes the kernels for the adjusted energy and force for a pair. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param rSquared the square of the internuclear distance * \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param kappaSquared the square of attenuation parameter in units inverse of those used to specify coordinates. * \return a tuple containing the energy and force kernels, respectively. */ template <int rPower> inline static std::tuple<Real, Real> adjEFImpl(Real rSquared, Real kappa, Real kappaSquared) { Real rInv = 1 / rSquared; Real kappaToRPower = kappa; for (int i = 1; i < rPower; ++i) kappaToRPower *= kappa; Real denominator = raiseNormToIntegerPower<Real, rPower>::compute(rSquared); Real gammaTerm = incompleteGammaComputer<Real, rPower>::compute(rSquared * kappaSquared) / gammaComputer<Real, rPower>::value; Real eKernel = (gammaTerm - 1) / denominator; Real fKernel = -rPower * eKernel * rInv - 2 * rInv * exp(-kappaSquared * rSquared) * kappaToRPower / gammaComputer<Real, rPower>::value; return std::make_tuple(eKernel, fKernel); } /*! * \brief slfEImpl computes the self energy due to particles feeling their own potential. * \tparam rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive dispersion). * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for quadrupoles, * etc.). * \param parameters the list of parameters associated with each atom (charges, C6 coefficients, multipoles, * etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = * (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param scaleFactor a scale factor to be applied to all computed energies and derivatives thereof * (e.g. the 1 / [4 pi epslion0] for Coulomb calculations). * \return the self energy. N.B. there is no self force associated with this term. */ template <int rPower> static Real slfEImpl(int parameterAngMom, const RealMat &parameters, Real kappa, Real scaleFactor) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); size_t nAtoms = parameters.nRows(); Real prefac = -scaleFactor * std::pow(kappa, rPower) / (rPower * gammaComputer<Real, rPower>::value); Real sumCoefs = 0; for (size_t atom = 0; atom < nAtoms; ++atom) { sumCoefs += parameters(atom, 0) * parameters(atom, 0); } return prefac * sumCoefs; } /*! * \brief common_init sets up information that is common to serial and parallel runs. */ void common_init(int rPower, Real kappa, int splineOrder, int dimA, int dimB, int dimC, Real scaleFactor, int nThreads) { kappaHasChanged_ = kappa != kappa_; rPowerHasChanged_ = rPower_ != rPower; gridDimensionHasChanged_ = dimA_ != dimA || dimB_ != dimB || dimC_ != dimC; splineOrderHasChanged_ = splineOrder_ != splineOrder; scaleFactorHasChanged_ = scaleFactor_ != scaleFactor; if (kappaHasChanged_ || rPowerHasChanged_ || gridDimensionHasChanged_ || splineOrderHasChanged_ || scaleFactorHasChanged_ || requestedNumberOfThreads_ != nThreads) { rPower_ = rPower; dimA_ = dimA; dimB_ = dimB; dimC_ = dimC; complexDimA_ = dimA / 2 + 1; myComplexDimA_ = myDimA_ / 2 + 1; splineOrder_ = splineOrder; requestedNumberOfThreads_ = nThreads; #ifdef _OPENMP nThreads_ = nThreads ? nThreads : omp_get_max_threads(); #else nThreads_ = 1; #endif scaleFactor_ = scaleFactor; kappa_ = kappa; cacheLineSizeInReals_ = static_cast<Real>(sysconf(_SC_PAGESIZE) / sizeof(Real)); // Helpers to perform 1D FFTs along each dimension. fftHelperA_ = FFTWWrapper<Real>(dimA_); fftHelperB_ = FFTWWrapper<Real>(dimB_); fftHelperC_ = FFTWWrapper<Real>(dimC_); // Grid iterators to correctly wrap the grid when using splines. gridIteratorA_ = makeGridIterator(dimA_, firstA_, lastA_); gridIteratorB_ = makeGridIterator(dimB_, firstB_, lastB_); gridIteratorC_ = makeGridIterator(dimC_, firstC_, lastC_); // Fourier space spline norms. Spline spline = Spline(0, 0, splineOrder_, 0); splineModA_ = spline.invSplineModuli(dimA_); splineModB_ = spline.invSplineModuli(dimB_); splineModC_ = spline.invSplineModuli(dimC_); // Set up function pointers by instantiating the appropriate evaluation functions. We could add many more // entries by default here, but don't right now to avoid code bloat. To add an extra rPower kernel is a // trivial cut and paste exercise; just add a new line with the desired 1/R power as the macro's argument. switch (rPower) { ENABLE_KERNEL_WITH_INVERSE_R_EXPONENT_OF(1); ENABLE_KERNEL_WITH_INVERSE_R_EXPONENT_OF(6); default: std::string msg("Bad rPower requested. To fix this, add the appropriate entry in"); msg += __FILE__; msg += ", line number "; msg += std::to_string(__LINE__ - 5); throw std::runtime_error(msg.c_str()); break; } subsetOfCAlongA_ = myDimC_ / numNodesA_; subsetOfCAlongB_ = myDimC_ / numNodesB_; subsetOfBAlongC_ = myDimB_ / numNodesC_; workSpace1_ = helpme::vector<Complex>(myDimC_ * myComplexDimA_ * myDimB_); workSpace2_ = helpme::vector<Complex>(myDimC_ * myComplexDimA_ * myDimB_); } } public: PMEInstance() : dimA_(0), dimB_(0), dimC_(0), splineOrder_(0), requestedNumberOfThreads_(-1), rPower_(0), scaleFactor_(0), kappa_(0), boxVecs_(3, 3), recVecs_(3, 3), scaledRecVecs_(3, 3), numNodesA_(1), numNodesB_(1), numNodesC_(1), cellA_(0), cellB_(0), cellC_(0), cellAlpha_(0), cellBeta_(0), cellGamma_(0) {} /*! * \brief cellVolume Compute the volume of the unit cell. * \return volume in units consistent with those used to define the lattice vectors. */ Real cellVolume() { return boxVecs_(0, 0) * boxVecs_(1, 1) * boxVecs_(2, 2) - boxVecs_(0, 0) * boxVecs_(1, 2) * boxVecs_(2, 1) + boxVecs_(0, 1) * boxVecs_(1, 2) * boxVecs_(2, 0) - boxVecs_(0, 1) * boxVecs_(1, 0) * boxVecs_(2, 2) + boxVecs_(0, 2) * boxVecs_(1, 0) * boxVecs_(2, 1) - boxVecs_(0, 2) * boxVecs_(1, 1) * boxVecs_(2, 0); } /*! * \brief Sets the unit cell lattice vectors, with units consistent with those used to specify coordinates. * \param A the A lattice parameter in units consistent with the coordinates. * \param B the B lattice parameter in units consistent with the coordinates. * \param C the C lattice parameter in units consistent with the coordinates. * \param alpha the alpha lattice parameter in degrees. * \param beta the beta lattice parameter in degrees. * \param gamma the gamma lattice parameter in degrees. * \param latticeType how to arrange the lattice vectors. Options are * ShapeMatrix: enforce a symmetric representation of the lattice vectors [c.f. S. Nosé and M. L. Klein, * Mol. Phys. 50 1055 (1983)] particularly appendix C. * XAligned: make the A vector coincide with the X axis, the B vector fall in the XY plane, and the C vector * take the appropriate alignment to completely define the system. */ void setLatticeVectors(Real A, Real B, Real C, Real alpha, Real beta, Real gamma, LatticeType latticeType) { if (A != cellA_ || B != cellB_ || C != cellC_ || alpha != cellAlpha_ || beta != cellBeta_ || gamma != cellGamma_ || latticeType != latticeType_) { if (latticeType == LatticeType::ShapeMatrix) { RealMat HtH(3, 3); HtH(0, 0) = A * A; HtH(1, 1) = B * B; HtH(2, 2) = C * C; const float TOL = 1e-4f; // Check for angles very close to 90, to avoid noise from the eigensolver later on. HtH(0, 1) = HtH(1, 0) = std::abs(gamma - 90) < TOL ? 0 : A * B * cos(M_PI * gamma / 180); HtH(0, 2) = HtH(2, 0) = std::abs(beta - 90) < TOL ? 0 : A * C * cos(M_PI * beta / 180); HtH(1, 2) = HtH(2, 1) = std::abs(alpha - 90) < TOL ? 0 : B * C * cos(M_PI * alpha / 180); auto eigenTuple = HtH.diagonalize(); RealMat evalsReal = std::get<0>(eigenTuple); RealMat evecs = std::get<1>(eigenTuple); for (int i = 0; i < 3; ++i) evalsReal(i, 0) = sqrt(evalsReal(i, 0)); boxVecs_.setZero(); for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 3; ++k) { boxVecs_(i, j) += evecs(i, k) * evecs(j, k) * evalsReal(k, 0); } } } recVecs_ = boxVecs_.inverse(); } else if (latticeType == LatticeType::XAligned) { boxVecs_(0, 0) = A; boxVecs_(0, 1) = 0; boxVecs_(0, 2) = 0; boxVecs_(1, 0) = B * cos(M_PI / 180 * gamma); boxVecs_(1, 1) = B * sin(M_PI / 180 * gamma); boxVecs_(1, 2) = 0; boxVecs_(2, 0) = C * cos(M_PI / 180 * beta); boxVecs_(2, 1) = (B * C * cos(M_PI / 180 * alpha) - boxVecs_(2, 0) * boxVecs_(1, 0)) / boxVecs_(1, 1); boxVecs_(2, 2) = sqrt(C * C - boxVecs_(2, 0) * boxVecs_(2, 0) - boxVecs_(2, 1) * boxVecs_(2, 1)); } else { throw std::runtime_error("Unknown lattice type in setLatticeVectors"); } recVecs_ = boxVecs_.inverse(); scaledRecVecs_ = recVecs_.clone(); scaledRecVecs_.row(0) *= dimA_; scaledRecVecs_.row(1) *= dimB_; scaledRecVecs_.row(2) *= dimC_; cellA_ = A; cellB_ = B; cellC_ = C; cellAlpha_ = alpha; cellBeta_ = beta; cellGamma_ = gamma; latticeType_ = latticeType; unitCellHasChanged_ = true; } else { unitCellHasChanged_ = false; } } /*! * \brief Performs the forward 3D FFT of the discretized parameter grid. * \param realGrid the array of discretized parameters (stored in CBA order, * with A being the fast running index) to be transformed. * \return Pointer to the transformed grid, which is stored in one of the buffers in BAC order. */ Complex *forwardTransform(Real *realGrid) { Real *realCBA; Complex *buffer1, *buffer2; if (realGrid == reinterpret_cast<Real *>(workSpace1_.data())) { realCBA = reinterpret_cast<Real *>(workSpace2_.data()); buffer1 = workSpace2_.data(); buffer2 = workSpace1_.data(); } else { realCBA = reinterpret_cast<Real *>(workSpace2_.data()); buffer1 = workSpace2_.data(); buffer2 = workSpace1_.data(); } #if HAVE_MPI == 1 if (numNodesA_ > 1) { // Communicate A along columns mpiCommunicatorA_->allToAll(realGrid, realCBA, subsetOfCAlongA_ * myDimA_ * myDimB_); // Resort the data to end up with realGrid holding a full row of A data, for B pencil and C subset. for (int c = 0; c < subsetOfCAlongA_; ++c) { Real *outC = realGrid + c * myDimB_ * dimA_; for (int b = 0; b < myDimB_; ++b) { for (int chunk = 0; chunk < numNodesA_; ++chunk) { Real *inPtr = realCBA + (chunk * subsetOfCAlongA_ + c) * myDimB_ * myDimA_ + b * myDimA_; std::copy(inPtr, inPtr + myDimA_, outC + b * dimA_ + chunk * myDimA_); } } } } #endif // Each parallel node allocates buffers of length dimA/(2 numNodesA)+1 for A, leading to a total of // dimA/2 + numNodesA = complexDimA+numNodesA-1 if dimA is even // and // numNodesA (dimA-1)/2 + numNodesA = complexDimA + numNodesA/2-1 if dimA is odd // We just allocate the larger size here, remembering that the final padding values on the last node // will all be allocated to zero and will not contribute to the final answer. helpme::vector<Complex> buffer(complexDimA_ + numNodesA_ - 1); // A transform, with instant sort to CAB ordering for each local block auto scratch = buffer.data(); for (int c = 0; c < subsetOfCAlongA_; ++c) { for (int b = 0; b < myDimB_; ++b) { Real *gridPtr = realGrid + c * myDimB_ * dimA_ + b * dimA_; fftHelperA_.transform(gridPtr, scratch); for (int chunk = 0; chunk < numNodesA_; ++chunk) { for (int a = 0; a < myComplexDimA_; ++a) { buffer1[(chunk * subsetOfCAlongA_ + c) * myComplexDimA_ * myDimB_ + a * myDimB_ + b] = scratch[chunk * myComplexDimA_ + a]; } } } } #if HAVE_MPI == 1 // Communicate A back to blocks if (numNodesA_ > 1) { mpiCommunicatorA_->allToAll(buffer1, buffer2, subsetOfCAlongA_ * myComplexDimA_ * myDimB_); std::swap(buffer1, buffer2); } // Communicate B along rows if (numNodesB_ > 1) { mpiCommunicatorB_->allToAll(buffer1, buffer2, subsetOfCAlongB_ * myComplexDimA_ * myDimB_); // Resort the data to end up with the buffer holding a full row of B data, for A pencil and C subset. for (int c = 0; c < subsetOfCAlongB_; ++c) { Complex *cPtr = buffer1 + c * myComplexDimA_ * dimB_; for (int a = 0; a < myComplexDimA_; ++a) { for (int chunk = 0; chunk < numNodesB_; ++chunk) { Complex *inPtr = buffer2 + (chunk * subsetOfCAlongB_ + c) * myComplexDimA_ * myDimB_ + a * myDimB_; std::copy(inPtr, inPtr + myDimB_, cPtr + a * dimB_ + chunk * myDimB_); } } } } #endif // B transform for (int c = 0; c < subsetOfCAlongB_; ++c) { Complex *cPtr = buffer1 + c * myComplexDimA_ * dimB_; for (int a = 0; a < myComplexDimA_; ++a) { fftHelperB_.transform(cPtr + a * dimB_, FFTW_FORWARD); } } #if HAVE_MPI == 1 if (numNodesB_ > 1) { for (int c = 0; c < subsetOfCAlongB_; ++c) { Complex *zPtr = buffer1 + c * myComplexDimA_ * dimB_; for (int a = 0; a < myComplexDimA_; ++a) { for (int chunk = 0; chunk < numNodesB_; ++chunk) { Complex *inPtr = zPtr + a * dimB_ + chunk * myDimB_; Complex *outPtr = buffer2 + (chunk * subsetOfCAlongB_ + c) * myComplexDimA_ * myDimB_ + a * myDimB_; std::copy(inPtr, inPtr + myDimB_, outPtr); } } } // Communicate B back to blocks mpiCommunicatorB_->allToAll(buffer2, buffer1, subsetOfCAlongB_ * myComplexDimA_ * myDimB_); } #endif // sort local blocks from CAB to BAC order for (int b = 0; b < myDimB_; ++b) { for (int a = 0; a < myComplexDimA_; ++a) { for (int c = 0; c < myDimC_; ++c) { buffer2[b * myComplexDimA_ * myDimC_ + a * myDimC_ + c] = buffer1[c * myComplexDimA_ * myDimB_ + a * myDimB_ + b]; } } } #if HAVE_MPI == 1 if (numNodesC_ > 1) { // Communicate C along columns mpiCommunicatorC_->allToAll(buffer2, buffer1, subsetOfBAlongC_ * myComplexDimA_ * myDimC_); for (int b = 0; b < subsetOfBAlongC_; ++b) { Complex *outPtrB = buffer2 + b * myComplexDimA_ * dimC_; for (int a = 0; a < myComplexDimA_; ++a) { Complex *outPtrBA = outPtrB + a * dimC_; for (int chunk = 0; chunk < numNodesC_; ++chunk) { Complex *inPtr = buffer1 + (chunk * subsetOfBAlongC_ + b) * myComplexDimA_ * myDimC_ + a * myDimC_; std::copy(inPtr, inPtr + myDimC_, outPtrBA + chunk * myDimC_); } } } } #endif // C transform for (int b = 0; b < subsetOfBAlongC_; ++b) { Complex *outPtrB = buffer2 + b * myComplexDimA_ * dimC_; for (int a = 0; a < myComplexDimA_; ++a) { Complex *outPtrBA = outPtrB + a * dimC_; fftHelperC_.transform(outPtrBA, FFTW_FORWARD); } } return buffer2; } /*! * \brief Performs the inverse 3D FFT. * \param convolvedGrid the complex array of discretized parameters convolved with the influence function * (stored in BAC order, with C being the fast running index) to be transformed. * \return Pointer to the potential grid, which is stored in one of the buffers in CBA order. */ Real *inverseTransform(Complex *convolvedGrid) { Complex *buffer1, *buffer2; // Setup scratch, taking care not to overwrite the convolved grid. if (convolvedGrid == workSpace1_.data()) { buffer1 = workSpace2_.data(); buffer2 = workSpace1_.data(); } else { buffer1 = workSpace1_.data(); buffer2 = workSpace2_.data(); } // C transform for (int y = 0; y < subsetOfBAlongC_; ++y) { for (int x = 0; x < myComplexDimA_; ++x) { int yx = y * myComplexDimA_ * dimC_ + x * dimC_; fftHelperC_.transform(convolvedGrid + yx, FFTW_BACKWARD); } } #if HAVE_MPI == 1 if (numNodesC_ > 1) { // Communicate C back to blocks for (int b = 0; b < subsetOfBAlongC_; ++b) { Complex *inPtrB = convolvedGrid + b * myComplexDimA_ * dimC_; for (int a = 0; a < myComplexDimA_; ++a) { Complex *inPtrBA = inPtrB + a * dimC_; for (int chunk = 0; chunk < numNodesC_; ++chunk) { Complex *inPtrBAC = inPtrBA + chunk * myDimC_; Complex *outPtr = buffer1 + (chunk * subsetOfBAlongC_ + b) * myComplexDimA_ * myDimC_ + a * myDimC_; std::copy(inPtrBAC, inPtrBAC + myDimC_, outPtr); } } } mpiCommunicatorC_->allToAll(buffer1, buffer2, subsetOfBAlongC_ * myComplexDimA_ * myDimC_); } #endif // sort local blocks from BAC to CAB order for (int B = 0; B < myDimB_; ++B) { for (int A = 0; A < myComplexDimA_; ++A) { for (int C = 0; C < myDimC_; ++C) { buffer1[C * myComplexDimA_ * myDimB_ + A * myDimB_ + B] = buffer2[B * myComplexDimA_ * myDimC_ + A * myDimC_ + C]; } } } #if HAVE_MPI == 1 // Communicate B along rows if (numNodesB_ > 1) { mpiCommunicatorB_->allToAll(buffer1, buffer2, subsetOfCAlongB_ * myComplexDimA_ * myDimB_); // Resort the data to end up with the buffer holding a full row of B data, for A pencil and C subset. for (int c = 0; c < subsetOfCAlongB_; ++c) { Complex *cPtr = buffer1 + c * myComplexDimA_ * dimB_; for (int a = 0; a < myComplexDimA_; ++a) { for (int chunk = 0; chunk < numNodesB_; ++chunk) { Complex *inPtr = buffer2 + (chunk * subsetOfCAlongB_ + c) * myComplexDimA_ * myDimB_ + a * myDimB_; std::copy(inPtr, inPtr + myDimB_, cPtr + a * dimB_ + chunk * myDimB_); } } } } #endif // B transform with instant sort of local blocks from CAB -> CBA order for (int c = 0; c < subsetOfCAlongB_; ++c) { for (int a = 0; a < myComplexDimA_; ++a) { int cx = c * myComplexDimA_ * dimB_ + a * dimB_; fftHelperB_.transform(buffer1 + cx, FFTW_BACKWARD); for (int b = 0; b < myDimB_; ++b) { for (int chunk = 0; chunk < numNodesB_; ++chunk) { int cb = (chunk * subsetOfCAlongB_ + c) * myDimB_ * myComplexDimA_ + b * myComplexDimA_; buffer2[cb + a] = buffer1[cx + chunk * myDimB_ + b]; } } } } #if HAVE_MPI == 1 // Communicate B back to blocks if (numNodesB_ > 1) { mpiCommunicatorB_->allToAll(buffer2, buffer1, subsetOfCAlongB_ * myComplexDimA_ * myDimB_); } else { std::swap(buffer1, buffer2); } // Communicate A along rows if (numNodesA_ > 1) { mpiCommunicatorA_->allToAll(buffer1, buffer2, subsetOfCAlongA_ * myComplexDimA_ * myDimB_); // Resort the data to end up with the buffer holding a full row of A data, for B pencil and C subset. for (int c = 0; c < subsetOfCAlongA_; ++c) { Complex *cPtr = buffer1 + c * myDimB_ * complexDimA_; for (int b = 0; b < myDimB_; ++b) { for (int chunk = 0; chunk < numNodesA_; ++chunk) { Complex *inPtr = buffer2 + (chunk * subsetOfCAlongA_ + c) * myComplexDimA_ * myDimB_ + b * myComplexDimA_; std::copy(inPtr, inPtr + myComplexDimA_, cPtr + b * complexDimA_ + chunk * myComplexDimA_); } } } } #else std::swap(buffer1, buffer2); #endif // A transform Real *realGrid = reinterpret_cast<Real *>(buffer2); for (int cb = 0; cb < subsetOfCAlongA_ * myDimB_; ++cb) { fftHelperA_.transform(buffer1 + cb * complexDimA_, realGrid + cb * dimA_); } #if HAVE_MPI == 1 // Communicate A back to blocks if (numNodesA_ > 1) { Real *realGrid2 = reinterpret_cast<Real *>(buffer1); for (int c = 0; c < subsetOfCAlongA_; ++c) { Real *cPtr = realGrid + c * myDimB_ * dimA_; for (int b = 0; b < myDimB_; ++b) { for (int chunk = 0; chunk < numNodesA_; ++chunk) { Real *outPtr = realGrid2 + (chunk * subsetOfCAlongA_ + c) * myDimB_ * myDimA_ + b * myDimA_; Real *inPtr = cPtr + b * dimA_ + chunk * myDimA_; std::copy(inPtr, inPtr + myDimA_, outPtr); } } } mpiCommunicatorA_->allToAll(realGrid2, realGrid, subsetOfCAlongA_ * myDimB_ * myDimA_); } #endif return realGrid; } /*! * \brief convolveE A wrapper to determine the correct convolution function to call. * \param transformedGrid the pointer to the complex array holding the transformed grid in YXZ ordering. * \return the reciprocal space energy. */ Real convolveE(Complex *transformedGrid) { updateInfluenceFunction(); size_t myNy = myDimB_ / numNodesC_; size_t myNx = myComplexDimA_; size_t nz = dimC_; size_t nxz = myNx * nz; size_t nyxz = myNy * nxz; size_t halfNx = dimA_ / 2 + 1; bool iAmNodeZero = (rankA_ == 0 && rankB_ == 0 && rankC_ == 0); Real *influenceFunction = cachedInfluenceFunction_.data(); int startX = rankA_ * myComplexDimA_; Real energy = 0; if (rPower_ > 3 && iAmNodeZero) { // Kernels with rPower>3 are absolutely convergent and should have the m=0 term present. // To compute it we need sum_ij c(i)c(j), which can be obtained from the structure factor norm. Real prefac = 2 * scaleFactor_ * M_PI * sqrtPi * pow(kappa_, rPower_ - 3) / ((rPower_ - 3) * nonTemplateGammaComputer<Real>(rPower_) * cellVolume()); energy += prefac * std::norm(transformedGrid[0]); } transformedGrid[0] = Complex(0, 0); #pragma omp parallel for reduction(+ : energy) num_threads(nThreads_) for (size_t yxz = 0; yxz < nyxz; ++yxz) { size_t xz = yxz % nxz; int kx = startX + xz / nz; // We only loop over the first nx/2+1 x values; this // accounts for the "missing" complex conjugate values. Real permPrefac = kx != 0 && kx != halfNx - 1 ? 2 : 1; Real structFactorNorm = std::norm(transformedGrid[yxz]); energy += permPrefac * structFactorNorm * influenceFunction[yxz]; transformedGrid[yxz] *= influenceFunction[yxz]; } return energy / 2; } /*! * \brief convolveEV A wrapper to determine the correct convolution function to call, including virial. * \param transformedGrid the pointer to the complex array holding the transformed grid in YXZ ordering. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \return the reciprocal space energy. */ Real convolveEV(Complex *transformedGrid, RealMat &virial) { return convolveEVFxn_(dimA_, dimB_, dimC_, myComplexDimA_, myDimB_ / numNodesC_, rankA_ * myComplexDimA_, rankB_ * myDimB_ + rankC_ * myDimB_ / numNodesC_, scaleFactor_, transformedGrid, recVecs_, cellVolume(), kappa_, &splineModA_[0], &splineModB_[0], &splineModC_[0], virial, nThreads_); } /*! * \brief Spread the parameters onto the charge grid. Generally this shouldn't be called; * use the various computeE() methods instead. This the more efficient version that filters * the atom list and uses pre-computed splines. Therefore, the splineCache_ * member must have been updated via a call to filterAtomsAndBuildSplineCache() first. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \return realGrid the array of discretized parameters (stored in CBA order). */ Real *spreadParameters(int parameterAngMom, const RealMat &parameters) { Real *realGrid = reinterpret_cast<Real *>(workSpace1_.data()); std::fill(workSpace1_.begin(), workSpace1_.end(), 0); updateAngMomIterator(parameterAngMom); size_t nAtoms = atomList_.size(); int nComponents = nCartesian(parameterAngMom); for (size_t relativeAtomNumber = 0; relativeAtomNumber < nAtoms; ++relativeAtomNumber) { const auto &entry = splineCache_[relativeAtomNumber]; const int &atom = entry.absoluteAtomNumber; const auto &splineA = entry.aSpline; const auto &splineB = entry.bSpline; const auto &splineC = entry.cSpline; spreadParametersImpl(atom, realGrid, nComponents, splineA, splineB, splineC, parameters); } return realGrid; } /*! * \brief Spread the parameters onto the charge grid. Generally this shouldn't be called; * use the various computeE() methods instead. This is the slower version of this call that recomputes * splines on demand and makes no assumptions about the integrity of the spline cache. * \param parameterAngMom the angular momentum of the parameters * (0 for charges, C6 coefficients, 2 for quadrupoles, etc.). * \param parameters the list of parameters associated with each atom (charges, C6 coefficients, multipoles, * etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = * (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \return realGrid the array of discretized parameters (stored in CBA order). */ Real *spreadParameters(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { Real *realGrid = reinterpret_cast<Real *>(workSpace1_.data()); std::fill(workSpace1_.begin(), workSpace1_.end(), 0); updateAngMomIterator(parameterAngMom); int nComponents = nCartesian(parameterAngMom); size_t nAtoms = coordinates.nRows(); for (size_t atom = 0; atom < nAtoms; ++atom) { // Blindly reconstruct splines for this atom, assuming nothing about the validity of the cache. // Note that this incurs a somewhat steep cost due to repeated memory allocations. auto bSplines = makeBSplines(coordinates[atom], parameterAngMom); const auto &splineA = std::get<0>(bSplines); const auto &splineB = std::get<1>(bSplines); const auto &splineC = std::get<2>(bSplines); spreadParametersImpl(atom, realGrid, nComponents, splineA, splineB, splineC, parameters); } return realGrid; } /*! * \brief Probes the potential grid to get the forces. Generally this shouldn't be called; * use the various computeE() methods instead. This is the slower version of this call that recomputes * splines on demand and makes no assumptions about the integrity of the spline cache. * \param potentialGrid pointer to the array containing the potential, in ZYX order. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. */ void probeGrid(const Real *potentialGrid, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces) { updateAngMomIterator(parameterAngMom + 1); int nComponents = nCartesian(parameterAngMom); int nForceComponents = nCartesian(parameterAngMom + 1); RealMat fractionalPhis(1, nForceComponents); size_t nAtoms = parameters.nRows(); for (size_t atom = 0; atom < nAtoms; ++atom) { auto bSplines = makeBSplines(coordinates[atom], parameterAngMom + 1); auto splineA = std::get<0>(bSplines); auto splineB = std::get<1>(bSplines); auto splineC = std::get<2>(bSplines); probeGridImpl(atom, potentialGrid, nComponents, nForceComponents, splineA, splineB, splineC, fractionalPhis[0], parameters, forces[atom]); } } /*! * \brief Probes the potential grid to get the forces. Generally this shouldn't be called; * use the various computeE() methods instead. This is the faster version that uses * the filtered atom list and uses pre-computed splines. Therefore, the splineCache_ * member must have been updated via a call to filterAtomsAndBuildSplineCache() first. * * \param potentialGrid pointer to the array containing the potential, in ZYX order. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. */ void probeGrid(const Real *potentialGrid, int parameterAngMom, const RealMat &parameters, RealMat &forces) { updateAngMomIterator(parameterAngMom + 1); int nComponents = nCartesian(parameterAngMom); int nForceComponents = nCartesian(parameterAngMom + 1); const Real *paramPtr = parameters[0]; // Find how many multiples of the cache line size are needed // to ensure that each thread hits a unique page. size_t rowSize = std::ceil(nForceComponents / cacheLineSizeInReals_) * cacheLineSizeInReals_; RealMat fractionalPhis(nThreads_, rowSize); size_t nAtoms = atomList_.size(); #pragma omp parallel for num_threads(nThreads_) for (size_t relativeAtomNumber = 0; relativeAtomNumber < nAtoms; ++relativeAtomNumber) { const auto &entry = splineCache_[relativeAtomNumber]; const int &atom = entry.absoluteAtomNumber; const auto &splineA = entry.aSpline; const auto &splineB = entry.bSpline; const auto &splineC = entry.cSpline; if (parameterAngMom) { #ifdef _OPENMP int threadID = omp_get_thread_num(); #else int threadID = 1; #endif Real *myScratch = fractionalPhis[threadID % nThreads_]; probeGridImpl(atom, potentialGrid, nComponents, nForceComponents, splineA, splineB, splineC, myScratch, parameters, forces[atom]); } else { probeGridImpl(potentialGrid, splineA, splineB, splineC, paramPtr[atom], forces[atom]); } } } /*! * \brief computeESlf computes the Ewald self interaction energy. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \return the self energy. */ Real computeESlf(int parameterAngMom, const RealMat &parameters) { assertInitialized(); return slfEFxn_(parameterAngMom, parameters, kappa_, scaleFactor_); } /*! * \brief computeEDir computes the direct space energy. This is provided mostly for debugging and testing * purposes; generally the host program should provide the pairwise interactions. \param pairList dense list of * atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. \param parameterAngMom the angular momentum of * the parameters (0 for charges, C6 coefficients, 2 for quadrupoles, etc.). \param parameters the list of * parameters associated with each atom (charges, C6 coefficients, multipoles, etc...). For a parameter with * angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the * fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \return the direct space energy. */ Real computeEDir(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); energy += parameters(i, 0) * parameters(j, 0) * dirEFxn_(rSquared, kappaSquared); } return scaleFactor_ * energy; } /*! * \brief computeEFDir computes the direct space energy and force. This is provided mostly for debugging and * testing purposes; generally the host program should provide the pairwise interactions. * \param pairList dense list of atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \return the direct space energy. */ Real computeEFDir(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); auto kernels = dirEFFxn_(rSquared, kappa_, kappaSquared); Real eKernel = std::get<0>(kernels); Real fKernel = std::get<1>(kernels); Real prefactor = scaleFactor_ * parameters(i, 0) * parameters(j, 0); energy += prefactor * eKernel; Real f = -prefactor * fKernel; auto force = deltaR.row(0); force *= f; forces.row(i) -= force; forces.row(j) += force; } return energy; } /*! * \brief computeEFVDir computes the direct space energy, force and virial. This is provided mostly for * debugging and testing purposes; generally the host program should provide the pairwise interactions. \param * pairList dense list of atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. \param parameterAngMom * the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for quadrupoles, etc.). \param * parameters the list of parameters associated with each atom (charges, C6 coefficients, multipoles, etc...). * For a parameter with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = * (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \return the direct space energy. */ Real computeEFVDir(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces, RealMat &virial) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); auto kernels = dirEFFxn_(rSquared, kappa_, kappaSquared); Real eKernel = std::get<0>(kernels); Real fKernel = std::get<1>(kernels); Real prefactor = scaleFactor_ * parameters(i, 0) * parameters(j, 0); energy += prefactor * eKernel; Real f = -prefactor * fKernel; RealMat dRCopy = deltaR.clone(); auto force = dRCopy.row(0); force *= f; forces.row(i) -= force; forces.row(j) += force; virial[0][0] += force[0] * deltaR[0][0]; virial[0][1] += 0.5f * (force[0] * deltaR[0][1] + force[1] * deltaR[0][0]); virial[0][2] += force[1] * deltaR[0][1]; virial[0][3] += 0.5f * (force[0] * deltaR[0][2] + force[2] * deltaR[0][0]); virial[0][4] += 0.5f * (force[1] * deltaR[0][2] + force[2] * deltaR[0][1]); virial[0][5] += force[2] * deltaR[0][2]; } return energy; } /*! * \brief computeEAdj computes the adjusted real space energy which extracts the energy for excluded pairs that * is present in reciprocal space. This is provided mostly for debugging and testing purposes; generally the * host program should provide the pairwise interactions. * \param pairList dense list of atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \return the adjusted energy. */ Real computeEAdj(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); energy += parameters(i, 0) * parameters(j, 0) * adjEFxn_(rSquared, kappaSquared); } return scaleFactor_ * energy; } /*! * \brief computeEFAdj computes the adjusted energy and force. This is provided mostly for debugging and * testing purposes; generally the host program should provide the pairwise interactions. \param pairList dense * list of atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. \param parameterAngMom the angular * momentum of the parameters (0 for charges, C6 coefficients, 2 for quadrupoles, etc.). \param parameters the * list of parameters associated with each atom (charges, C6 coefficients, multipoles, etc...). For a parameter * with angular momentum L, a matrix of dimension nAtoms x nL is expected, where nL = (L+1)*(L+2)*(L+3)/6 and * the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \return the adjusted energy. */ Real computeEFAdj(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); auto kernels = adjEFFxn_(rSquared, kappa_, kappaSquared); Real eKernel = std::get<0>(kernels); Real fKernel = std::get<1>(kernels); Real prefactor = scaleFactor_ * parameters(i, 0) * parameters(j, 0); energy += prefactor * eKernel; Real f = -prefactor * fKernel; auto force = deltaR.row(0); force *= f; forces.row(i) -= force; forces.row(j) += force; } return energy; } /*! * \brief computeEFVAdj computes the adjusted energy, forces and virial. This is provided mostly for debugging * and testing purposes; generally the host program should provide the pairwise interactions. * \param pairList dense list of atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \return the adjusted energy. */ Real computeEFVAdj(const Matrix<short> &pairList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces, RealMat &virial) { if (parameterAngMom) throw std::runtime_error("Multipole self terms have not been coded yet."); sanityChecks(parameterAngMom, parameters, coordinates); Real energy = 0; Real kappaSquared = kappa_ * kappa_; size_t nPair = pairList.nRows(); for (int pair = 0; pair < nPair; ++pair) { short i = pairList(pair, 0); short j = pairList(pair, 1); auto deltaR = coordinates.row(j) - coordinates.row(i); // TODO: apply minimum image convention. Real rSquared = deltaR.dot(deltaR); auto kernels = adjEFFxn_(rSquared, kappa_, kappaSquared); Real eKernel = std::get<0>(kernels); Real fKernel = std::get<1>(kernels); Real prefactor = scaleFactor_ * parameters(i, 0) * parameters(j, 0); energy += prefactor * eKernel; Real f = -prefactor * fKernel; RealMat dRCopy = deltaR.clone(); auto force = dRCopy.row(0); force *= f; forces.row(i) -= force; forces.row(j) += force; virial[0][0] += force[0] * deltaR[0][0]; virial[0][1] += 0.5f * (force[0] * deltaR[0][1] + force[1] * deltaR[0][0]); virial[0][2] += force[1] * deltaR[0][1]; virial[0][3] += 0.5f * (force[0] * deltaR[0][2] + force[2] * deltaR[0][0]); virial[0][4] += 0.5f * (force[1] * deltaR[0][2] + force[2] * deltaR[0][1]); virial[0][5] += force[2] * deltaR[0][2]; } return energy; } /*! * \brief Runs a PME reciprocal space calculation, computing the potential and, optionally, its derivatives. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param gridPoints the list of grid points at which the potential is needed; can be the same as the * coordinates. \param derivativeLevel the order of the potential derivatives required; 0 is the potential, 1 is * (minus) the field, etc. \param potential the array holding the potential. This is a matrix of dimensions * nAtoms x nD, where nD is the derivative level requested. See the details fo the parameters argument for * information about ordering of derivative components. N.B. this array is incremented with the potential, not * assigned, so take care to zero it first if only the current results are desired. */ void computePRec(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, const RealMat &gridPoints, int derivativeLevel, RealMat &potential) { sanityChecks(parameterAngMom, parameters, coordinates); updateAngMomIterator(std::max(parameterAngMom, derivativeLevel)); // Note: we're calling the version of spread parameters that computes its own splines here. // This is quite inefficient, but allow the potential to be computed at arbitrary locations by // simply regenerating splines on demand in the probing stage. If this becomes too slow, it's // easy to write some logic to check whether gridPoints and coordinates are the same, and // handle that special case using spline cacheing machinery for efficiency. auto realGrid = spreadParameters(parameterAngMom, parameters, coordinates); auto gridAddress = forwardTransform(realGrid); convolveE(gridAddress); const auto potentialGrid = inverseTransform(gridAddress); auto fracPotential = potential.clone(); int nPotentialComponents = nCartesian(derivativeLevel); size_t nPoints = gridPoints.nRows(); for (size_t point = 0; point < nPoints; ++point) { auto bSplines = makeBSplines(gridPoints[point], derivativeLevel); auto splineA = std::get<0>(bSplines); auto splineB = std::get<1>(bSplines); auto splineC = std::get<2>(bSplines); probeGridImpl(potentialGrid, nPotentialComponents, splineA, splineB, splineC, fracPotential[point]); } potential += cartesianTransform(derivativeLevel, scaledRecVecs_, fracPotential); } /*! * \brief Runs a PME reciprocal space calculation, computing energies. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \return the reciprocal space energy. */ Real computeERec(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { sanityChecks(parameterAngMom, parameters, coordinates); filterAtomsAndBuildSplineCache(parameterAngMom, coordinates); auto realGrid = spreadParameters(parameterAngMom, parameters); auto gridAddress = forwardTransform(realGrid); return convolveE(gridAddress); } /*! * \brief Runs a PME reciprocal space calculation, computing energies and forces. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \return the reciprocal space energy. */ Real computeEFRec(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces) { sanityChecks(parameterAngMom, parameters, coordinates); // Spline derivative level bumped by 1, for energy gradients. filterAtomsAndBuildSplineCache(parameterAngMom + 1, coordinates); auto realGrid = spreadParameters(parameterAngMom, parameters); auto gridAddress = forwardTransform(realGrid); Real energy = convolveE(gridAddress); const auto potentialGrid = inverseTransform(gridAddress); probeGrid(potentialGrid, parameterAngMom, parameters, forces); return energy; } /*! * \brief Runs a PME reciprocal space calculation, computing energies, forces and the virial. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \return the reciprocal space energy. */ Real computeEFVRec(int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces, RealMat &virial) { sanityChecks(parameterAngMom, parameters, coordinates); // Spline derivative level bumped by 1, for energy gradients. filterAtomsAndBuildSplineCache(parameterAngMom + 1, coordinates); auto realGrid = spreadParameters(parameterAngMom, parameters); auto gridPtr = forwardTransform(realGrid); Real energy = convolveEV(gridPtr, virial); const auto potentialGrid = inverseTransform(gridPtr); probeGrid(potentialGrid, parameterAngMom, parameters, forces); return energy; } /*! * \brief Runs a full (direct and reciprocal space) PME calculation, computing the energy. The direct space * implementation here is not totally optimal, so this routine should primarily be used for testing and * debugging. * \param includedList dense list of included atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN,jN. * \param excludedList dense list of excluded atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \return the full PME energy. */ Real computeEAll(const Matrix<short> &includedList, const Matrix<short> &excludedList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates) { sanityChecks(parameterAngMom, parameters, coordinates); Real energy = computeERec(parameterAngMom, parameters, coordinates); energy += computeESlf(parameterAngMom, parameters); energy += computeEDir(includedList, parameterAngMom, parameters, coordinates); energy += computeEAdj(excludedList, parameterAngMom, parameters, coordinates); return energy; } /*! * \brief Runs a full (direct and reciprocal space) PME calculation, computing energies and forces. The direct * space implementation here is not totally optimal, so this routine should primarily be used for testing * and debugging. * \param includedList dense list of included atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param excludedList dense list of excluded atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \return the full PME energy. */ Real computeEFAll(const Matrix<short> &includedList, const Matrix<short> &excludedList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces) { sanityChecks(parameterAngMom, parameters, coordinates); Real energy = computeEFRec(parameterAngMom, parameters, coordinates, forces); energy += computeESlf(parameterAngMom, parameters); energy += computeEFDir(includedList, parameterAngMom, parameters, coordinates, forces); energy += computeEFAdj(excludedList, parameterAngMom, parameters, coordinates, forces); return energy; } /*! * \brief Runs a full (direct and reciprocal space) PME calculation, computing energies, forces and virials. * The direct space implementation here is not totally optimal, so this routine should primarily * be used for testing and debugging. * \param includedList dense list of included atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param excludedList dense list of excluded atom pairs, ordered like i1, j1, i2, j2, i3, j3, ... iN, jN. * \param parameterAngMom the angular momentum of the parameters (0 for charges, C6 coefficients, 2 for * quadrupoles, etc.). \param parameters the list of parameters associated with each atom (charges, C6 * coefficients, multipoles, etc...). For a parameter with angular momentum L, a matrix of dimension nAtoms x nL * is expected, where nL = (L+1)*(L+2)*(L+3)/6 and the fast running index nL has the ordering * * 0 X Y Z XX XY YY XZ YZ ZZ XXX XXY XYY YYY XXZ XYZ YYZ XZZ YZZ ZZZ ... * * i.e. generated by the python loops * \code{.py} * for L in range(maxAM+1): * for Lz in range(0,L+1): * for Ly in range(0, L - Lz + 1): * Lx = L - Ly - Lz * \endcode * \param coordinates the cartesian coordinates, ordered in memory as {x1,y1,z1,x2,y2,z2,....xN,yN,zN}. * \param energy pointer to the variable holding the energy; this is incremented, not assigned. * \param forces a Nx3 matrix of the forces, ordered in memory as {Fx1,Fy1,Fz1,Fx2,Fy2,Fz2,....FxN,FyN,FzN}. * This matrix is incremented, not assigned. * \param virial a vector of length 6 containing the unique virial elements, in the order XX XY YY XZ YZ ZZ. * This vector is incremented, not assigned. * \return the full PME energy. */ Real computeEFVAll(const Matrix<short> &includedList, const Matrix<short> &excludedList, int parameterAngMom, const RealMat &parameters, const RealMat &coordinates, RealMat &forces, RealMat &virial) { sanityChecks(parameterAngMom, parameters, coordinates); Real energy = computeEFVRec(parameterAngMom, parameters, coordinates, forces, virial); energy += computeESlf(parameterAngMom, parameters); energy += computeEFVDir(includedList, parameterAngMom, parameters, coordinates, forces, virial); energy += computeEFVAdj(excludedList, parameterAngMom, parameters, coordinates, forces, virial); return energy; } /*! * \brief setup initializes this object for a PME calculation using only threading. * This may be called repeatedly without compromising performance. * \param rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive * dispersion). \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param splineOrder the order of B-spline; must be at least (2 + max. multipole order + deriv. level needed). * \param dimA the dimension of the FFT grid along the A axis. * \param dimB the dimension of the FFT grid along the B axis. * \param dimC the dimension of the FFT grid along the C axis. * \param scaleFactor a scale factor to be applied to all computed energies and derivatives thereof (e.g. the * 1 / [4 pi epslion0] for Coulomb calculations). * \param nThreads the maximum number of threads to use for each MPI instance; if set to 0 all available threads * are used. */ void setup(int rPower, Real kappa, int splineOrder, int dimA, int dimB, int dimC, Real scaleFactor, int nThreads) { numNodesHasChanged_ = numNodesA_ != 1 || numNodesB_ != 1 || numNodesC_ != 1; numNodesA_ = numNodesB_ = numNodesC_ = 1; rankA_ = rankB_ = rankC_ = 0; firstA_ = firstB_ = firstC_ = 0; dimA = findGridSize(dimA, {1}); dimB = findGridSize(dimB, {1}); dimC = findGridSize(dimC, {1}); lastA_ = dimA; lastB_ = dimB; lastC_ = dimC; myDimA_ = dimA; myDimB_ = dimB; myDimC_ = dimC; common_init(rPower, kappa, splineOrder, dimA, dimB, dimC, scaleFactor, nThreads); } /*! * \brief setup initializes this object for a PME calculation using MPI parallism and threading. * This may be called repeatedly without compromising performance. * \param rPower the exponent of the (inverse) distance kernel (e.g. 1 for Coulomb, 6 for attractive * dispersion). \param kappa the attenuation parameter in units inverse of those used to specify coordinates. * \param splineOrder the order of B-spline; must be at least (2 + max. multipole order + deriv. level needed). * \param dimA the dimension of the FFT grid along the A axis. * \param dimB the dimension of the FFT grid along the B axis. * \param dimC the dimension of the FFT grid along the C axis. * \param scaleFactor a scale factor to be applied to all computed energies and derivatives thereof (e.g. the * 1 / [4 pi epslion0] for Coulomb calculations). * \param nThreads the maximum number of threads to use for each MPI instance; if set to 0 all available threads * are \param communicator the MPI communicator for the reciprocal space calcultion, which should already be * initialized. * \param numNodesA the number of nodes to be used for the A dimension. * \param numNodesB the number of nodes to be used for the B dimension. * \param numNodesC the number of nodes to be used for the C dimension. */ void setupParallel(int rPower, Real kappa, int splineOrder, int dimA, int dimB, int dimC, Real scaleFactor, int nThreads, const MPI_Comm &communicator, NodeOrder nodeOrder, int numNodesA, int numNodesB, int numNodesC) { numNodesHasChanged_ = numNodesA_ != numNodesA || numNodesB_ != numNodesB || numNodesC_ != numNodesC; #if HAVE_MPI == 1 mpiCommunicator_ = std::unique_ptr<MPIWrapper<Real>>(new MPIWrapper<Real>(communicator, numNodesA, numNodesB, numNodesC)); switch (nodeOrder) { case (NodeOrder::ZYX): rankA_ = mpiCommunicator_->myRank_ % numNodesA; rankB_ = (mpiCommunicator_->myRank_ % (numNodesB * numNodesA)) / numNodesA; rankC_ = mpiCommunicator_->myRank_ / (numNodesB * numNodesA); mpiCommunicatorA_ = mpiCommunicator_->split(rankC_ * numNodesB + rankB_, rankA_); mpiCommunicatorB_ = mpiCommunicator_->split(rankC_ * numNodesA + rankA_, rankB_); mpiCommunicatorC_ = mpiCommunicator_->split(rankB_ * numNodesA + rankA_, rankC_); break; default: throw std::runtime_error("Unknown NodeOrder in setupParallel."); } numNodesA_ = numNodesA; numNodesB_ = numNodesB; numNodesC_ = numNodesC; dimA = findGridSize(dimA, {numNodesA}); dimB = findGridSize(dimB, {numNodesB * numNodesC}); dimC = findGridSize(dimC, {numNodesA * numNodesC, numNodesB * numNodesC}); myDimA_ = dimA / numNodesA; myDimB_ = dimB / numNodesB; myDimC_ = dimC / numNodesC; firstA_ = rankA_ * myDimA_; firstB_ = rankB_ * myDimB_; firstC_ = rankC_ * myDimC_; lastA_ = rankA_ == numNodesA ? dimA : (rankA_ + 1) * myDimA_; lastB_ = rankB_ == numNodesB ? dimB : (rankB_ + 1) * myDimB_; lastC_ = rankC_ == numNodesC ? dimC : (rankC_ + 1) * myDimC_; common_init(rPower, kappa, splineOrder, dimA, dimB, dimC, scaleFactor, nThreads); #else // Have MPI throw std::runtime_error( "setupParallel called, but helpme was not compiled with MPI. Make sure you compile with -DHAVE_MPI=1 " "in " "the list of compiler definitions."); #endif // Have MPI } }; } // Namespace helpme using PMEInstanceD = helpme::PMEInstance<double>; using PMEInstanceF = helpme::PMEInstance<float>; #else // C header #include <stddef.h> #if HAVE_MPI == 1 #include <mpi.h> #endif typedef enum { XAligned = 0, ShapeMatrix = 1 } LatticeType; typedef enum { ZYX = 0 } NodeOrder; typedef struct PMEInstance PMEInstance; extern struct PMEInstance *helpme_createD(); extern struct PMEInstance *helpme_createF(); extern void helpme_destroyD(struct PMEInstance *pme); extern void helpme_destroyF(struct PMEInstance *pme); extern void helpme_setupD(struct PMEInstance *pme, int rPower, double kappa, int splineOrder, int aDim, int bDim, int cDim, double scaleFactor, int nThreads); extern void helpme_setupF(struct PMEInstance *pme, int rPower, float kappa, int splineOrder, int aDim, int bDim, int cDim, float scaleFactor, int nThreads); #if HAVE_MPI == 1 extern void helpme_setup_parallelD(PMEInstance *pme, int rPower, double kappa, int splineOrder, int dimA, int dimB, int dimC, double scaleFactor, int nThreads, MPI_Comm communicator, NodeOrder nodeOrder, int numNodesA, int numNodesB, int numNodesC); extern void helpme_setup_parallelF(PMEInstance *pme, int rPower, float kappa, int splineOrder, int dimA, int dimB, int dimC, float scaleFactor, int nThreads, MPI_Comm communicator, NodeOrder nodeOrder, int numNodesA, int numNodesB, int numNodesC); #endif // HAVE_MPI extern void helpme_set_lattice_vectorsD(struct PMEInstance *pme, double A, double B, double C, double kappa, double beta, double gamma, LatticeType latticeType); extern void helpme_set_lattice_vectorsF(struct PMEInstance *pme, float A, float B, float C, float kappa, float beta, float gamma, LatticeType latticeType); extern double helpme_compute_E_recD(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, double *parameters, double *coordinates); extern float helpme_compute_E_recF(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, float *parameters, float *coordinates); extern double helpme_compute_EF_recD(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, double *parameters, double *coordinates, double *forces); extern float helpme_compute_EF_recF(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, float *parameters, float *coordinates, float *forces); extern double helpme_compute_EFV_recD(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, double *parameters, double *coordinates, double *forces, double *virial); extern float helpme_compute_EFV_recF(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, float *parameters, float *coordinates, float *forces, float *virial); extern void helpme_compute_P_recD(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, double *parameters, double *coordinates, size_t nGridPoints, double *gridPoints, int derivativeLevel, double *potential); extern void helpme_compute_P_recF(struct PMEInstance *pme, size_t nAtoms, int parameterAngMom, float *parameters, float *coordinates, size_t nGridPoints, float *gridPoints, int derivativeLevel, float *potential); #endif // C++/C #endif // Header guard
core_zsyrk.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "core_lapack.h" /***************************************************************************//** * * @ingroup core_syrk * * Performs one of the symmetric rank k operations * * \f[ C = \alpha A \times A^T + \beta C, \f] * or * \f[ C = \alpha A^T \times A + \beta C, \f] * * where alpha and beta are scalars, C is an n-by-n symmetric * matrix, and A is an n-by-k matrix in the first case and a k-by-n * matrix in the second case. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of C is stored; * - PlasmaLower: Lower triangle of C is stored. * * @param[in] trans * - PlasmaNoTrans: \f[ C = \alpha A \times A^T + \beta C; \f] * - PlasmaTrans: \f[ C = \alpha A^T \times A + \beta C. \f] * * @param[in] n * The order of the matrix C. n >= 0. * * @param[in] k * If trans = PlasmaNoTrans, number of columns of the A matrix; * if trans = PlasmaTrans, number of rows of the A matrix. * * @param[in] alpha * The scalar alpha. * * @param[in] A * A is an lda-by-ka matrix. * If trans = PlasmaNoTrans, ka = k; * if trans = PlasmaTrans, ka = n. * * @param[in] lda * The leading dimension of the array A. * If trans = PlasmaNoTrans, lda >= max(1, n); * if trans = PlasmaTrans, lda >= max(1, k). * * @param[in] beta * The scalar beta. * * @param[in,out] C * C is an ldc-by-n matrix. * On exit, the uplo part of the matrix is overwritten * by the uplo part of the updated matrix. * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1, n). * ******************************************************************************/ void core_zsyrk(plasma_enum_t uplo, plasma_enum_t trans, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, plasma_complex64_t beta, plasma_complex64_t *C, int ldc) { cblas_zsyrk(CblasColMajor, (CBLAS_UPLO)uplo, (CBLAS_TRANSPOSE)trans, n, k, CBLAS_SADDR(alpha), A, lda, CBLAS_SADDR(beta), C, ldc); } /******************************************************************************/ void core_omp_zsyrk( plasma_enum_t uplo, plasma_enum_t trans, int n, int k, plasma_complex64_t alpha, const plasma_complex64_t *A, int lda, plasma_complex64_t beta, plasma_complex64_t *C, int ldc, plasma_sequence_t *sequence, plasma_request_t *request) { int ak; if (trans == PlasmaNoTrans) ak = k; else ak = n; #pragma omp task depend(in:A[0:lda*ak]) \ depend(inout:C[0:ldc*n]) { if (sequence->status == PlasmaSuccess) core_zsyrk(uplo, trans, n, k, alpha, A, lda, beta, C, ldc); } }
ZQ_CNN_BBoxUtils.h
#ifndef _ZQ_CNN_BBOX_UTILS_H_ #define _ZQ_CNN_BBOX_UTILS_H_ #pragma once #include "ZQ_CNN_BBox.h" #include <string> #include <math.h> #include <algorithm> namespace ZQ { class ZQ_CNN_BBoxUtils { public: enum PriorBoxCodeType { PriorBoxCodeType_CORNER = 0, PriorBoxCodeType_CORNER_SIZE, PriorBoxCodeType_CENTER_SIZE }; static bool _cmp_score(const ZQ_CNN_OrderScore& lsh, const ZQ_CNN_OrderScore& rsh) { return lsh.score < rsh.score; } static void _nms(std::vector<ZQ_CNN_BBox> &boundingBox, std::vector<ZQ_CNN_OrderScore> &bboxScore, const float overlap_threshold, const std::string& modelname = "Union", int overlap_count_thresh = 0, int thread_num = 1) { if (boundingBox.empty() || overlap_threshold >= 1.0) { return; } std::vector<int> heros; std::vector<int> overlap_num; //sort the score sort(bboxScore.begin(), bboxScore.end(), _cmp_score); int order = 0; float IOU = 0; float maxX = 0; float maxY = 0; float minX = 0; float minY = 0; while (bboxScore.size() > 0) { order = bboxScore.back().oriOrder; bboxScore.pop_back(); if (order < 0)continue; heros.push_back(order); int cur_overlap = 0; boundingBox[order].exist = false;//delete it int box_num = boundingBox.size(); if (thread_num == 1) { for (int num = 0; num < box_num; num++) { if (boundingBox[num].exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { cur_overlap++; boundingBox[num].exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } } else { int chunk_size = ceil(box_num / thread_num); #pragma omp parallel for schedule(static, chunk_size) num_threads(thread_num) for (int num = 0; num < box_num; num++) { if (boundingBox.at(num).exist) { //the iou maxY = __max(boundingBox[num].row1, boundingBox[order].row1); maxX = __max(boundingBox[num].col1, boundingBox[order].col1); minY = __min(boundingBox[num].row2, boundingBox[order].row2); minX = __min(boundingBox[num].col2, boundingBox[order].col2); //maxX1 and maxY1 reuse maxX = __max(minX - maxX + 1, 0); maxY = __max(minY - maxY + 1, 0); //IOU reuse for the area of two bbox IOU = maxX * maxY; float area1 = boundingBox[num].area; float area2 = boundingBox[order].area; if (!modelname.compare("Union")) IOU = IOU / (area1 + area2 - IOU); else if (!modelname.compare("Min")) { IOU = IOU / __min(area1, area2); } if (IOU > overlap_threshold) { cur_overlap++; boundingBox.at(num).exist = false; for (std::vector<ZQ_CNN_OrderScore>::iterator it = bboxScore.begin(); it != bboxScore.end(); it++) { if ((*it).oriOrder == num) { (*it).oriOrder = -1; break; } } } } } } overlap_num.push_back(cur_overlap); } for (int i = 0; i < heros.size(); i++) { if(!boundingBox[heros[i]].need_check_overlap_count || overlap_num[i] >= overlap_count_thresh) boundingBox[heros[i]].exist = true; } //clear exist= false; for (int i = boundingBox.size() - 1; i >= 0; i--) { if (!boundingBox[i].exist) { boundingBox.erase(boundingBox.begin() + i); } } } static void _refine_and_square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height, bool square = true) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { bbh = (*it).row2 - (*it).row1 + 1; bbw = (*it).col2 - (*it).col1 + 1; y1 = (*it).row1 + (*it).regreCoord[1] * bbh; x1 = (*it).col1 + (*it).regreCoord[0] * bbw; y2 = (*it).row2 + (*it).regreCoord[3] * bbh; x2 = (*it).col2 + (*it).regreCoord[2] * bbw; w = x2 - x1 + 1; h = y2 - y1 + 1; if (square) { bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } else { (*it).row2 = round(y1 + h - 1); (*it).col2 = round(x1 + w - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); } //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } static void _square_bbox(std::vector<ZQ_CNN_BBox> &vecBbox, const int width, const int height) { float bbw = 0, bbh = 0, bboxSize = 0; float h = 0, w = 0; float x1 = 0, y1 = 0, x2 = 0, y2 = 0; for (std::vector<ZQ_CNN_BBox>::iterator it = vecBbox.begin(); it != vecBbox.end(); it++) { if ((*it).exist) { y1 = (*it).row1; x1 = (*it).col1; h = (*it).row2 - (*it).row1 + 1; w = (*it).col2 - (*it).col1 + 1; bboxSize = (h > w) ? h : w; y1 = y1 + h*0.5 - bboxSize*0.5; x1 = x1 + w*0.5 - bboxSize*0.5; (*it).row2 = round(y1 + bboxSize - 1); (*it).col2 = round(x1 + bboxSize - 1); (*it).row1 = round(y1); (*it).col1 = round(x1); //boundary check /*if ((*it).row1 < 0)(*it).row1 = 0; if ((*it).col1 < 0)(*it).col1 = 0; if ((*it).row2 > height)(*it).row2 = height - 1; if ((*it).col2 > width)(*it).col2 = width - 1;*/ it->area = (it->row2 - it->row1)*(it->col2 - it->col1); } } } static bool DecodeBBoxesAll(const std::vector<ZQ_CNN_LabelBBox>& all_loc_preds, const std::vector<ZQ_CNN_NormalizedBBox>& prior_bboxes, const std::vector<std::vector<float> >& prior_variances, const int num, const bool share_location, const int num_loc_classes, const int background_label_id, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip, std::vector<ZQ_CNN_LabelBBox>* all_decode_bboxes) { if (all_loc_preds.size() != num) return false; all_decode_bboxes->clear(); all_decode_bboxes->resize(num); for (int i = 0; i < num; ++i) { // Decode predictions into bboxes. ZQ_CNN_LabelBBox& decode_bboxes = (*all_decode_bboxes)[i]; for (int c = 0; c < num_loc_classes; ++c) { int label = share_location ? -1 : c; if (label == background_label_id) { // Ignore background class. continue; } if (all_loc_preds[i].find(label) == all_loc_preds[i].end()) { // Something bad happened if there are no predictions for current label. //LOG(FATAL) << "Could not find location predictions for label " << label; } const std::vector<ZQ_CNN_NormalizedBBox>& label_loc_preds = all_loc_preds[i].find(label)->second; if (!DecodeBBoxes(prior_bboxes, prior_variances, code_type, variance_encoded_in_target, clip, label_loc_preds, &(decode_bboxes[label]))) return false; } } return true; } static bool DecodeBBoxes( const std::vector<ZQ_CNN_NormalizedBBox>& prior_bboxes, const std::vector<std::vector<float> >& prior_variances, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip_bbox, const std::vector<ZQ_CNN_NormalizedBBox>& bboxes, std::vector<ZQ_CNN_NormalizedBBox>* decode_bboxes) { if (prior_bboxes.size() != prior_variances.size()) return false; if (prior_bboxes.size() != bboxes.size()) return false; int num_bboxes = prior_bboxes.size(); if (num_bboxes >= 1) { if (prior_variances[0].size() != 4) return false; } decode_bboxes->clear(); for (int i = 0; i < num_bboxes; ++i) { ZQ_CNN_NormalizedBBox decode_bbox; if (!DecodeBBox(prior_bboxes[i], prior_variances[i], code_type, variance_encoded_in_target, clip_bbox, bboxes[i], &decode_bbox)) return false; decode_bboxes->push_back(decode_bbox); } return true; } static bool DecodeBBox( const ZQ_CNN_NormalizedBBox& prior_bbox, const std::vector<float>& prior_variance, const PriorBoxCodeType code_type, const bool variance_encoded_in_target, const bool clip_bbox, const ZQ_CNN_NormalizedBBox& bbox, ZQ_CNN_NormalizedBBox* decode_bbox) { if (code_type == PriorBoxCodeType_CORNER) { if (variance_encoded_in_target) { // variance is encoded in target, we simply need to add the offset // predictions. decode_bbox->col1 = prior_bbox.col1 + bbox.col1; decode_bbox->col2 = prior_bbox.col2 + bbox.col2; decode_bbox->row1 = prior_bbox.row1 + bbox.row1; decode_bbox->row2 = prior_bbox.row2 + bbox.row2; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox->col1 = prior_bbox.col1 + prior_variance[0] * bbox.col1; decode_bbox->row1 = prior_bbox.row1 + prior_variance[1] * bbox.row1; decode_bbox->col2 = prior_bbox.col2 + prior_variance[2] * bbox.col2; decode_bbox->row2 = prior_bbox.row2 + prior_variance[3] * bbox.row2; } } else if (code_type == PriorBoxCodeType_CENTER_SIZE) { float prior_width = prior_bbox.col2 - prior_bbox.col1; if (prior_width < 0) { // return false; printf("x = [%f , %f]\n", prior_bbox.col1, prior_bbox.col2); } float prior_height = prior_bbox.row2 - prior_bbox.row1; if (prior_height < 0) { //return false; printf("y = [%f , %f]\n", prior_bbox.row1, prior_bbox.row2); } float prior_center_x = (prior_bbox.col1 + prior_bbox.col2) / 2.; float prior_center_y = (prior_bbox.row1 + prior_bbox.row2) / 2.; float decode_bbox_center_x, decode_bbox_center_y; float decode_bbox_width, decode_bbox_height; if (variance_encoded_in_target) { // variance is encoded in target, we simply need to retore the offset // predictions. decode_bbox_center_x = bbox.col1 * prior_width + prior_center_x; decode_bbox_center_y = bbox.row1 * prior_height + prior_center_y; decode_bbox_width = exp(bbox.col2) * prior_width; decode_bbox_height = exp(bbox.row2) * prior_height; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox_center_x = prior_variance[0] * bbox.col1 * prior_width + prior_center_x; decode_bbox_center_y = prior_variance[1] * bbox.row1 * prior_height + prior_center_y; decode_bbox_width = exp(prior_variance[2] * bbox.col2) * prior_width; decode_bbox_height = exp(prior_variance[3] * bbox.row2) * prior_height; } decode_bbox->col1 = decode_bbox_center_x - decode_bbox_width / 2.; decode_bbox->row1 = decode_bbox_center_y - decode_bbox_height / 2.; decode_bbox->col2 = decode_bbox_center_x + decode_bbox_width / 2.; decode_bbox->row2 = decode_bbox_center_y + decode_bbox_height / 2.; } else if (code_type == PriorBoxCodeType_CORNER_SIZE) { float prior_width = prior_bbox.col2 - prior_bbox.col1; if (prior_width < 0) { //return false; printf("x = [%f , %f]\n", prior_bbox.col1, prior_bbox.col2); } float prior_height = prior_bbox.row2 - prior_bbox.row1; if (prior_height < 0) { // return false; printf("y = [%f , %f]\n", prior_bbox.row1, prior_bbox.row2); } if (variance_encoded_in_target) { // variance is encoded in target, we simply need to add the offset // predictions. decode_bbox->col1 = prior_bbox.col1 + bbox.col1 * prior_width; decode_bbox->row1 = prior_bbox.row1 + bbox.row1 * prior_height; decode_bbox->col2 = prior_bbox.col2 + bbox.col2 * prior_width; decode_bbox->row2 = prior_bbox.row2 + bbox.row2 * prior_height; } else { // variance is encoded in bbox, we need to scale the offset accordingly. decode_bbox->col1 = prior_bbox.col1 + prior_variance[0] * bbox.col1 * prior_width; decode_bbox->row1 = prior_bbox.row1 + prior_variance[1] * bbox.row1 * prior_height; decode_bbox->col2 = prior_bbox.col2 + prior_variance[2] * bbox.col2 * prior_width; decode_bbox->row2 = prior_bbox.row2 + prior_variance[3] * bbox.row2 * prior_height; } } else { printf("unknown code type\n"); return false; } float bbox_size = BBoxSize(*decode_bbox, true); decode_bbox->size = bbox_size; if (clip_bbox) { ClipBBox(*decode_bbox, decode_bbox); } return true; } static float BBoxSize(const ZQ_CNN_NormalizedBBox& bbox, const bool normalized) { if (bbox.col2 < bbox.col1 || bbox.row2 < bbox.row1) { // If bbox is invalid (e.g. xmax < xmin or ymax < ymin), return 0. return 0; } else { float width = bbox.col2 - bbox.col1; float height = bbox.row2 - bbox.row1; if (normalized) { return width * height; } else { // If bbox is not within range [0, 1]. return (width + 1) * (height + 1); } } } static void ClipBBox(const ZQ_CNN_NormalizedBBox& bbox, ZQ_CNN_NormalizedBBox* clip_bbox) { clip_bbox->col1 = std::max(std::min(bbox.col1, 1.f), 0.f); clip_bbox->row1 = std::max(std::min(bbox.row1, 1.f), 0.f); clip_bbox->col2 = std::max(std::min(bbox.col2, 1.f), 0.f); clip_bbox->row2 = std::max(std::min(bbox.row2, 1.f), 0.f); clip_bbox->size = BBoxSize(*clip_bbox, true); clip_bbox->difficult = bbox.difficult; } static bool GetLocPredictions(const float* loc_data, const int num, const int num_preds_per_class, const int num_loc_classes, const bool share_location, std::vector<ZQ_CNN_LabelBBox>* loc_preds) { loc_preds->clear(); if (share_location) { if (num_loc_classes != 1) return false; } loc_preds->resize(num); for (int i = 0; i < num; i++) { ZQ_CNN_LabelBBox& label_bbox = (*loc_preds)[i]; for (int p = 0; p < num_preds_per_class; p++) { int start_idx = p * num_loc_classes * 4; for (int c = 0; c < num_loc_classes; c++) { int label = share_location ? -1 : c; if (label_bbox.find(label) == label_bbox.end()) { label_bbox[label].resize(num_preds_per_class); } label_bbox[label][p].col1 = loc_data[start_idx + c * 4]; label_bbox[label][p].row1 = loc_data[start_idx + c * 4 + 1]; label_bbox[label][p].col2 = loc_data[start_idx + c * 4 + 2]; label_bbox[label][p].row2 = loc_data[start_idx + c * 4 + 3]; } } loc_data += num_preds_per_class * num_loc_classes * 4; } return true; } static void TransformLocations_MXNET(float *out, const float *anchors, const float *loc_pred, const bool clip, const float vx, const float vy, const float vw, const float vh) { // transform predictions to detection results float al = anchors[0]; float at = anchors[1]; float ar = anchors[2]; float ab = anchors[3]; float aw = ar - al; float ah = ab - at; float ax = (al + ar) / 2.f; float ay = (at + ab) / 2.f; float px = loc_pred[0]; float py = loc_pred[1]; float pw = loc_pred[2]; float ph = loc_pred[3]; float ox = px * vx * aw + ax; float oy = py * vy * ah + ay; float ow = exp(pw * vw) * aw / 2; float oh = exp(ph * vh) * ah / 2; out[0] = clip ? __max(0, __min(1, ox - ow)) : (ox - ow); out[1] = clip ? __max(0, __min(1, oy - oh)) : (oy - oh); out[2] = clip ? __max(0, __min(1, ox + ow)) : (ox + ow); out[3] = clip ? __max(0, __min(1, oy + oh)) : (oy + oh); } static void GetConfidenceScores(const float* conf_data, const int num, const int num_preds_per_class, const int num_classes, std::vector<std::map<int, std::vector<float> > >* conf_preds) { conf_preds->clear(); conf_preds->resize(num); for (int i = 0; i < num; ++i) { std::map<int, std::vector<float> >& label_scores = (*conf_preds)[i]; for (int p = 0; p < num_preds_per_class; ++p) { int start_idx = p * num_classes; for (int c = 0; c < num_classes; ++c) { label_scores[c].push_back(conf_data[start_idx + c]); } } conf_data += num_preds_per_class * num_classes; } } static void GetConfidenceScores(const float* conf_data, const int num, const int num_preds_per_class, const int num_classes, const bool class_major, std::vector<std::map<int, std::vector<float> > >* conf_preds) { conf_preds->clear(); conf_preds->resize(num); for (int i = 0; i < num; ++i) { std::map<int, std::vector<float> >& label_scores = (*conf_preds)[i]; if (class_major) { for (int c = 0; c < num_classes; ++c) { label_scores[c].assign(conf_data, conf_data + num_preds_per_class); conf_data += num_preds_per_class; } } else { for (int p = 0; p < num_preds_per_class; ++p) { int start_idx = p * num_classes; for (int c = 0; c < num_classes; ++c) { label_scores[c].push_back(conf_data[start_idx + c]); } } conf_data += num_preds_per_class * num_classes; } } } static void GetPriorBBoxes(const float* prior_data, const int num_priors, std::vector<ZQ_CNN_NormalizedBBox>* prior_bboxes, std::vector<std::vector<float> >* prior_variances) { prior_bboxes->clear(); prior_variances->clear(); for (int i = 0; i < num_priors; ++i) { int start_idx = i * 4; ZQ_CNN_NormalizedBBox bbox; bbox.col1 = prior_data[start_idx]; bbox.row1 = prior_data[start_idx + 1]; bbox.col2 = prior_data[start_idx + 2]; bbox.row2 = prior_data[start_idx + 3]; float bbox_size = BBoxSize(bbox, true); bbox.size = bbox_size; prior_bboxes->push_back(bbox); } for (int i = 0; i < num_priors;i++) { int start_idx = (num_priors + i) * 4; std::vector<float> var; for (int j = 0; j < 4; ++j) { var.push_back(prior_data[start_idx + j]); } prior_variances->push_back(var); } } static bool ApplyNMSFast(const std::vector<ZQ_CNN_NormalizedBBox>& bboxes, const std::vector<float>& scores, const float score_threshold, const float nms_threshold, const float eta, const int top_k, std::vector<int>* indices) { // Sanity check. if (bboxes.size() != scores.size()) { printf("bboxes and scores have different size.\n"); return false; } // Get top_k scores (with corresponding indices). std::vector<std::pair<float, int> > score_index_vec; GetMaxScoreIndex(scores, score_threshold, top_k, &score_index_vec); // Do nms. float adaptive_threshold = nms_threshold; indices->clear(); while (score_index_vec.size() != 0) { const int idx = score_index_vec.front().second; bool keep = true; for (int k = 0; k < indices->size(); ++k) { if (keep) { const int kept_idx = (*indices)[k]; float overlap = JaccardOverlap(bboxes[idx], bboxes[kept_idx], true); keep = overlap <= adaptive_threshold; } else { break; } } if (keep) { indices->push_back(idx); } score_index_vec.erase(score_index_vec.begin()); if (keep && eta < 1 && adaptive_threshold > 0.5) { adaptive_threshold *= eta; } } return true; } static void GetMaxScoreIndex(const std::vector<float>& scores, const float threshold, const int top_k, std::vector<std::pair<float, int> >* score_index_vec) { // Generate index score pairs. for (int i = 0; i < scores.size(); ++i) { if (scores[i] > threshold) { score_index_vec->push_back(std::make_pair(scores[i], i)); } } // Sort the score pair according to the scores in descending order std::stable_sort(score_index_vec->begin(), score_index_vec->end(), SortScorePairDescend<int>); // Keep top_k scores if needed. if (top_k > -1 && top_k < score_index_vec->size()) { score_index_vec->resize(top_k); } } template <typename T> static bool SortScorePairDescend(const std::pair<float, T>& pair1, const std::pair<float, T>& pair2) { return pair1.first > pair2.first; } static float JaccardOverlap(const ZQ_CNN_NormalizedBBox& bbox1, const ZQ_CNN_NormalizedBBox& bbox2, const bool normalized) { ZQ_CNN_NormalizedBBox intersect_bbox; IntersectBBox(bbox1, bbox2, &intersect_bbox); float intersect_width, intersect_height; if (normalized) { intersect_width = intersect_bbox.col2 - intersect_bbox.col1; intersect_height = intersect_bbox.row2 - intersect_bbox.row1; } else { intersect_width = intersect_bbox.col2 - intersect_bbox.col1 + 1; intersect_height = intersect_bbox.row2 - intersect_bbox.row1 + 1; } if (intersect_width > 0 && intersect_height > 0) { float intersect_size = intersect_width * intersect_height; float bbox1_size = BBoxSize(bbox1, true); float bbox2_size = BBoxSize(bbox2, true); return intersect_size / (bbox1_size + bbox2_size - intersect_size); } else { return 0.; } } static void IntersectBBox(const ZQ_CNN_NormalizedBBox& bbox1, const ZQ_CNN_NormalizedBBox& bbox2, ZQ_CNN_NormalizedBBox* intersect_bbox) { if (bbox2.col1 > bbox1.col2 || bbox2.col2 < bbox1.col1 || bbox2.row1 > bbox1.row2 || bbox2.row2 < bbox1.row1) { // Return [0, 0, 0, 0] if there is no intersection. intersect_bbox->col1 = 0; intersect_bbox->row1 = 0; intersect_bbox->col2 = 0; intersect_bbox->row2 = 0; } else { intersect_bbox->col1 = std::max(bbox1.col1, bbox2.col1); intersect_bbox->row1 = std::max(bbox1.row1, bbox2.row1); intersect_bbox->col2 = std::min(bbox1.col2, bbox2.col2); intersect_bbox->row2 = std::min(bbox1.row2, bbox2.row2); } } }; } #endif
GB_unop__identity_fc32_bool.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_fc32_bool) // op(A') function: GB (_unop_tran__identity_fc32_bool) // C type: GxB_FC32_t // A type: bool // cast: GxB_FC32_t cij = GxB_CMPLXF ((float) (aij), 0) // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_FC32 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_fc32_bool) ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const bool *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; bool aij = Ax [p] ; GxB_FC32_t z = GxB_CMPLXF ((float) (aij), 0) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_fc32_bool) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
MD5_fmt.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 1996-2001,2008,2010-2012 by Solar Designer * * ...with changes in the jumbo patch, by bartavelle and magnum. * * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * There's ABSOLUTELY NO WARRANTY, express or implied. */ #include <string.h> #include "arch.h" #include "misc.h" #include "simd-intrinsics.h" #include "MD5_std.h" #include "common.h" #include "formats.h" #include "cryptmd5_common.h" #if defined(_OPENMP) && defined(SIMD_PARA_MD5) #ifndef OMP_SCALE #define OMP_SCALE 4 #endif #include <omp.h> #endif #include "memdbg.h" #define FORMAT_LABEL "md5crypt" #define FORMAT_NAME "crypt(3) $1$" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 15 #define CIPHERTEXT_LENGTH 22 #ifdef SIMD_PARA_MD5 #define BINARY_SIZE 16 #else #define BINARY_SIZE 4 #endif #define BINARY_ALIGN 4 #define SALT_SIZE 9 #define SALT_ALIGN 1 #define MIN_KEYS_PER_CRYPT MD5_N #define MAX_KEYS_PER_CRYPT MD5_N static struct fmt_tests tests[] = { {"$1$12345678$aIccj83HRDBo6ux1bVx7D1", "0123456789ABCDE"}, {"$apr1$Q6ZYh...$RV6ft2bZ8j.NGrxLYaJt9.", "test"}, {"$1$12345678$f8QoJuo0DpBRfQSD0vglc1", "12345678"}, {"$1$$qRPK7m23GJusamGpoGLby/", ""}, {"$apr1$a2Jqm...$grFrwEgiQleDr0zR4Jx1b.", "15 chars is max"}, {"$1$$AuJCr07mI7DSew03TmBIv/", "no salt"}, {"$1$`!@#%^&*$E6hD76/pKTS8qToBCkux30", "invalid salt"}, {"$1$12345678$xek.CpjQUVgdf/P2N9KQf/", ""}, {"$1$1234$BdIMOAWFOV2AQlLsrN/Sw.", "1234"}, {"$apr1$rBXqc...$NlXxN9myBOk95T0AyLAsJ0", "john"}, {"$apr1$Grpld/..$qp5GyjwM2dnA5Cdej9b411", "the"}, {"$apr1$GBx.D/..$yfVeeYFCIiEXInfRhBRpy/", "ripper"}, {"$1$bb$19smCEBG0Q1pVil0/HqK./", "aaaaa"}, {"$1$coin$rebm0t9KJ56mgGWJF5o5M0", "lapin"}, {"$1$pouet$/Ecz/vyk.zCYvrr6wB78h0", "canard"}, {"$1$test2$02MCIATVoxq3IhgK6XRkb1", "test1"}, {"$1$aussi$X67z3kXsWo92F15uChx1H1", "felicie"}, {"$1$boire$gf.YM2y3InYEu9.NbVr.v0", "manger"}, {"$1$bas$qvkmmWnVHRCSv/6LQ1doH/", "haut"}, {"$1$gauche$EPvd6LZlrgb0MMFPxUrJN1", "droite"}, /* following hashes are AIX non-standard smd5 hashes */ {"{smd5}s8/xSJ/v$uGam4GB8hOjTLQqvBfxJ2/", "password"}, {"{smd5}alRJaSLb$aKM3H1.h1ycXl5GEVDH1e1", "aixsucks?"}, {"{smd5}eLB0QWeS$Eg.YfWY8clZuCxF0xNrKg.", "0123456789ABCDE"}, /* following hashes are AIX standard smd5 hashes (with corrected tag) * lpa_options = std_hash=true */ {"$1$JVDbGx8K$T9h8HK4LZxeLPMTAxCfpc1", "password"}, {"$1$1Cu6fEvv$42kuaJ5fMEqyVStPuFG040", "0123456789ABCDE"}, {"$1$ql5x.xXL$vYVDhExol2xUBBpERRWcn1", "jtr>hashcat"}, {"$1$27iyq7Ya$miN09fW1Scj0DHVNyewoU/", ""}, {"$1$84Othc1n$v1cuReaa5lRdGuHaOa76n0", "a"}, {"$1$4zq0BsCR$U2ua9WZtDEhzy4gFSiLxN1", "aa"}, {"$1$DKwjKWxp$PY6PdlPZsXjOppPDoFOz4.", "aaa"}, {"$1$OKDV6ppN$viTVmH48bSePiCrMvXT/./", "aaaa"}, {"$1$QEWsCY0O$xrTTMKTepiHMp7Oxgz0pX/", "aaaaa"}, {"$1$5dfdk2dF$XiJBPNrfKcCgdQ/kcoB40/", "aaaaaa"}, {"$1$Ps6A1Cy6$WsvLg9cQhm9JU0rXkLEtz.", "aaaaaaa"}, {"$1$9IK7nZ4M$4nx7Mdj05KGPJX/mZaDrh.", "aaaaaaaa"}, {"$1$l3pNTqwT$GAc.dcRaxCvC20CFGCjp4/", "aaaaaaaaa"}, {"$1$jSAARhJR$6daQ/ekjAL0MgOUgGJyp10", "aaaaaaaaaa"}, {"$1$wk3Xwqqg$2AtdiucwJvJgbaVT1jWpb0", "aaaaaaaaaaa"}, {"$1$G6Fn69Ei$d7AKJUOIdz/gO4Utc0TQP1", "aaaaaaaaaaaa"}, {"$1$A7XJ7lGK$W5jTnH/4lW4XwZ.6F7n1N.", "aaaaaaaaaaaaa"}, {"$1$Rcm46RfA$LfdIK/OP16yHzMYHSlx/B.", "aaaaaaaaaaaaaa"}, {"$1$4bCSSJMN$TcYKTsukD4SFJE1n4MwMZ/", "aaaaaaaaaaaaaaa"}, #if PLAINTEXT_LENGTH > 15 {"$1$mJxBkkl8$u7OHfWCPmNxvf0um7hH89.", "aaaaaaaaaaaaaaaa"}, {"$1$Ub1gBUt4$TNaLxU7Pq5mk/MiDEb60b/", "aaaaaaaaaaaaaaaaa"}, {"$1$8ot7QScR$x.p4vjIgdFxxS83x29PkJ0", "aaaaaaaaaaaaaaaaaa"}, {"$1$wRi4OjD3$eJjKD2AwLMWfOTRYA30zn.", "aaaaaaaaaaaaaaaaaaa"}, {"$1$lmektrsg$2KSRY4EUFzsYNMg80fG4/0", "aaaaaaaaaaaaaaaaaaaa"}, {"$1$tgVBKBmE$YRvzsi7qHP2MC1Atg8VCV.", "aaaaaaaaaaaaaaaaaaaaa"}, {"$1$oTsk88YC$Eh435T1BQzmjQekfqkHof/", "aaaaaaaaaaaaaaaaaaaaaa"}, {"$1$ykxSZEfP$hJrFeGOFk049L.94Mgggj/", "aaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$LBK4p5tD$5/gAIx8/7hpTVwDC/.KQv/", "aaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$fkEasaUI$G7CelOWHkol2nVHN8XQP40", "aaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$gRevVzeY$eMMQrsl5OHL5dP1p/ktJc/", "aaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$164TNEjj$ppoV6Ju6Vu63j1OlM4zit/", "aaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$ErPmhjp2$lZZstb2M455Xhk50eeH4i/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$NUssS5fT$QaS4Ywt0IwzxbE0FAGnXn0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$NxlTyiJ7$gxkXTEJdeTzY8P6tqKmcz.", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$Cmy9x7gW$kamvHI42Kh1CH4Shy6g6S/", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$IsuapfCX$4Yq0Adq5nNZgl0LwbSl5Y0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, {"$1$rSZfNcKX$N4XPvGrfhKsyoEcRSaqmG0", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}, #endif {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; #ifdef SIMD_PARA_MD5 static unsigned char cursalt[SALT_SIZE]; static int CryptType; static MD5_word (*sout); static int omp_para = 1; #endif static void init(struct fmt_main *self) { MD5_std_init(self); #if defined(_OPENMP) && defined(SIMD_PARA_MD5) omp_para = omp_get_max_threads(); if (omp_para < 1) omp_para = 1; self->params.min_keys_per_crypt = MD5_N * omp_para; omp_para *= OMP_SCALE; self->params.max_keys_per_crypt = MD5_N * omp_para; #elif MD5_std_mt self->params.min_keys_per_crypt = MD5_std_min_kpc; self->params.max_keys_per_crypt = MD5_std_max_kpc; #endif saved_key = mem_calloc_align(self->params.max_keys_per_crypt, sizeof(*saved_key), MEM_ALIGN_CACHE); #ifdef SIMD_PARA_MD5 sout = mem_calloc(self->params.max_keys_per_crypt, sizeof(*sout) * BINARY_SIZE); #endif } static void done(void) { #ifdef SIMD_PARA_MD5 MEM_FREE(sout); #endif MEM_FREE(saved_key); } static int get_hash_0(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_0; #else init_t(); return MD5_out[index][0] & PH_MASK_0; #endif } static int get_hash_1(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_1; #else init_t(); return MD5_out[index][0] & PH_MASK_1; #endif } static int get_hash_2(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_2; #else init_t(); return MD5_out[index][0] & PH_MASK_2; #endif } static int get_hash_3(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_3; #else init_t(); return MD5_out[index][0] & PH_MASK_3; #endif } static int get_hash_4(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_4; #else init_t(); return MD5_out[index][0] & PH_MASK_4; #endif } static int get_hash_5(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_5; #else init_t(); return MD5_out[index][0] & PH_MASK_5; #endif } static int get_hash_6(int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; return ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] & PH_MASK_6; #else init_t(); return MD5_out[index][0] & PH_MASK_6; #endif } static int salt_hash(void *salt) { unsigned int i, h, retval; retval = 0; for (i = 0; i <= 6; i += 2) { h = (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i])]; h ^= ((unsigned char *)salt)[i + 1]; h <<= 6; h ^= (unsigned char)atoi64[ARCH_INDEX(((char *)salt)[i + 1])]; h ^= ((unsigned char *)salt)[i]; retval += h; } retval ^= retval >> SALT_HASH_LOG; retval &= SALT_HASH_SIZE - 1; return retval; } static void set_key(char *key, int index) { #ifndef SIMD_PARA_MD5 MD5_std_set_key(key, index); #endif strnfcpy(saved_key[index], key, PLAINTEXT_LENGTH); } static char *get_key(int index) { saved_key[index][PLAINTEXT_LENGTH] = 0; return saved_key[index]; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; #ifdef SIMD_PARA_MD5 #ifdef _OPENMP int t; #pragma omp parallel for for (t = 0; t < omp_para; t++) md5cryptsse((unsigned char *)(&saved_key[t*MD5_N]), cursalt, (char *)(&sout[t*MD5_N*BINARY_SIZE/sizeof(MD5_word)]), CryptType); #else md5cryptsse((unsigned char *)saved_key, cursalt, (char *)sout, CryptType); #endif #else MD5_std_crypt(count); #endif return count; } static int cmp_all(void *binary, int count) { #ifdef SIMD_PARA_MD5 unsigned int x,y; for (y=0;y<SIMD_PARA_MD5*omp_para;y++) for (x=0;x<SIMD_COEF_32;x++) { if ( ((MD5_word *)binary)[0] == ((MD5_word *)sout)[x+y*SIMD_COEF_32*4] ) return 1; } return 0; #else #if MD5_std_mt int t, n = (count + (MD5_N - 1)) / MD5_N; #endif for_each_t(n) { #if MD5_X2 if (*(MD5_word *)binary == MD5_out[0][0] || *(MD5_word *)binary == MD5_out[1][0]) return 1; #else if (*(MD5_word *)binary == MD5_out[0][0]) return 1; #endif } return 0; #endif } static int cmp_one(void *binary, int index) { #ifdef SIMD_PARA_MD5 unsigned int x,y; x = index&(SIMD_COEF_32-1); y = (unsigned int)index/SIMD_COEF_32; if (((unsigned int*)binary)[0] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+0*SIMD_COEF_32]) return 0; if (((unsigned int*)binary)[1] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+1*SIMD_COEF_32]) return 0; if (((unsigned int*)binary)[2] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+2*SIMD_COEF_32]) return 0; if (((unsigned int*)binary)[3] != ((unsigned int*)sout)[x+y*SIMD_COEF_32*4+3*SIMD_COEF_32]) return 0; return 1; #else init_t(); return *(MD5_word *)binary == MD5_out[index][0]; #endif } static int cmp_exact(char *source, int index) { #ifdef SIMD_PARA_MD5 return 1; #else init_t(); return !memcmp(MD5_std_get_binary(source), MD5_out[index], sizeof(MD5_binary)); #endif } static void set_salt(void *salt) { #ifdef SIMD_PARA_MD5 memcpy(cursalt, salt, SALT_SIZE); CryptType = cursalt[8]; cursalt[8] = 0; #endif MD5_std_set_salt(salt); } static void *get_salt(char *ciphertext) { return MD5_std_get_salt(ciphertext); } static void *get_binary(char *ciphertext) { return MD5_std_get_binary(ciphertext); } struct fmt_main fmt_MD5 = { { FORMAT_LABEL, FORMAT_NAME, "MD5 " MD5_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, #if MD5_std_mt || defined(SIMD_PARA_MD5) FMT_OMP | #endif FMT_CASE | FMT_8_BIT, { NULL }, { md5_salt_prefix, apr1_salt_prefix, smd5_salt_prefix }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, cryptmd5_common_valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } };
FillInLinearSystemImpl.h
// ---------------------------------------------------------------------------- // - Open3D: www.open3d.org - // ---------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2018-2021 www.open3d.org // // 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 "open3d/t/geometry/kernel/GeometryIndexer.h" #include "open3d/t/pipelines/kernel/FillInLinearSystem.h" #if defined(BUILD_CUDA_MODULE) && defined(__CUDACC__) #include "open3d/t/pipelines/kernel/SVD3x3CUDA.cuh" #else #include "open3d/t/pipelines/kernel/SVD3x3CPU.h" #endif namespace open3d { namespace t { namespace pipelines { namespace kernel { #if defined(__CUDACC__) void FillInRigidAlignmentTermCUDA #else void FillInRigidAlignmentTermCPU #endif (core::Tensor &AtA, core::Tensor &Atb, core::Tensor &residual, const core::Tensor &Ti_ps, const core::Tensor &Tj_qs, const core::Tensor &Ri_normal_ps, int i, int j, float threshold) { core::Device device = AtA.GetDevice(); int64_t n = Ti_ps.GetLength(); if (Tj_qs.GetLength() != n || Ri_normal_ps.GetLength() != n) { utility::LogError( "Unable to setup linear system: input length mismatch."); } // First fill in a small 12 x 12 linear system core::Tensor AtA_local = core::Tensor::Zeros({12, 12}, core::Dtype::Float32, device); core::Tensor Atb_local = core::Tensor::Zeros({12}, core::Dtype::Float32, device); float *AtA_local_ptr = static_cast<float *>(AtA_local.GetDataPtr()); float *Atb_local_ptr = static_cast<float *>(Atb_local.GetDataPtr()); float *residual_ptr = static_cast<float *>(residual.GetDataPtr()); const float *Ti_ps_ptr = static_cast<const float *>(Ti_ps.GetDataPtr()); const float *Tj_qs_ptr = static_cast<const float *>(Tj_qs.GetDataPtr()); const float *Ri_normal_ps_ptr = static_cast<const float *>(Ri_normal_ps.GetDataPtr()); #if defined(__CUDACC__) namespace launcher = core::kernel::cuda_launcher; #else namespace launcher = core::kernel::cpu_launcher; #endif launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t workload_idx) { const float *p_prime = Ti_ps_ptr + 3 * workload_idx; const float *q_prime = Tj_qs_ptr + 3 * workload_idx; const float *normal_p_prime = Ri_normal_ps_ptr + 3 * workload_idx; float r = (p_prime[0] - q_prime[0]) * normal_p_prime[0] + (p_prime[1] - q_prime[1]) * normal_p_prime[1] + (p_prime[2] - q_prime[2]) * normal_p_prime[2]; if (abs(r) > threshold) return; float J_ij[12]; J_ij[0] = -q_prime[2] * normal_p_prime[1] + q_prime[1] * normal_p_prime[2]; J_ij[1] = q_prime[2] * normal_p_prime[0] - q_prime[0] * normal_p_prime[2]; J_ij[2] = -q_prime[1] * normal_p_prime[0] + q_prime[0] * normal_p_prime[1]; J_ij[3] = normal_p_prime[0]; J_ij[4] = normal_p_prime[1]; J_ij[5] = normal_p_prime[2]; for (int k = 0; k < 6; ++k) { J_ij[k + 6] = -J_ij[k]; } // Not optimized; Switch to reduction if necessary. #if defined(BUILD_CUDA_MODULE) && defined(__CUDACC__) for (int i_local = 0; i_local < 12; ++i_local) { for (int j_local = 0; j_local < 12; ++j_local) { atomicAdd(&AtA_local_ptr[i_local * 12 + j_local], J_ij[i_local] * J_ij[j_local]); } atomicAdd(&Atb_local_ptr[i_local], J_ij[i_local] * r); } atomicAdd(residual_ptr, r * r); #else #pragma omp critical(FillInRigidAlignmentTermCPU) { for (int i_local = 0; i_local < 12; ++i_local) { for (int j_local = 0; j_local < 12; ++j_local) { AtA_local_ptr[i_local * 12 + j_local] += J_ij[i_local] * J_ij[j_local]; } Atb_local_ptr[i_local] += J_ij[i_local] * r; } *residual_ptr += r * r; } #endif }); // Then fill-in the large linear system std::vector<int64_t> indices_vec(12); for (int k = 0; k < 6; ++k) { indices_vec[k] = i * 6 + k; indices_vec[k + 6] = j * 6 + k; } std::vector<int64_t> indices_i_vec; std::vector<int64_t> indices_j_vec; for (int local_i = 0; local_i < 12; ++local_i) { for (int local_j = 0; local_j < 12; ++local_j) { indices_i_vec.push_back(indices_vec[local_i]); indices_j_vec.push_back(indices_vec[local_j]); } } core::Tensor indices(indices_vec, {12}, core::Dtype::Int64, device); core::Tensor indices_i(indices_i_vec, {12 * 12}, core::Dtype::Int64, device); core::Tensor indices_j(indices_j_vec, {12 * 12}, core::Dtype::Int64, device); core::Tensor AtA_sub = AtA.IndexGet({indices_i, indices_j}); AtA.IndexSet({indices_i, indices_j}, AtA_sub + AtA_local.View({12 * 12})); core::Tensor Atb_sub = Atb.IndexGet({indices}); Atb.IndexSet({indices}, Atb_sub + Atb_local.View({12, 1})); } #if defined(__CUDACC__) void FillInSLACAlignmentTermCUDA #else void FillInSLACAlignmentTermCPU #endif (core::Tensor &AtA, core::Tensor &Atb, core::Tensor &residual, const core::Tensor &Ti_Cps, const core::Tensor &Tj_Cqs, const core::Tensor &Cnormal_ps, const core::Tensor &Ri_Cnormal_ps, const core::Tensor &RjT_Ri_Cnormal_ps, const core::Tensor &cgrid_idx_ps, const core::Tensor &cgrid_idx_qs, const core::Tensor &cgrid_ratio_qs, const core::Tensor &cgrid_ratio_ps, int i, int j, int n_frags, float threshold) { int64_t n = Ti_Cps.GetLength(); if (Tj_Cqs.GetLength() != n || Cnormal_ps.GetLength() != n || Ri_Cnormal_ps.GetLength() != n || RjT_Ri_Cnormal_ps.GetLength() != n || cgrid_idx_ps.GetLength() != n || cgrid_ratio_ps.GetLength() != n || cgrid_idx_qs.GetLength() != n || cgrid_ratio_qs.GetLength() != n) { utility::LogError( "Unable to setup linear system: input length mismatch."); } int n_vars = Atb.GetLength(); float *AtA_ptr = static_cast<float *>(AtA.GetDataPtr()); float *Atb_ptr = static_cast<float *>(Atb.GetDataPtr()); float *residual_ptr = static_cast<float *>(residual.GetDataPtr()); // Geometric properties const float *Ti_Cps_ptr = static_cast<const float *>(Ti_Cps.GetDataPtr()); const float *Tj_Cqs_ptr = static_cast<const float *>(Tj_Cqs.GetDataPtr()); const float *Cnormal_ps_ptr = static_cast<const float *>(Cnormal_ps.GetDataPtr()); const float *Ri_Cnormal_ps_ptr = static_cast<const float *>(Ri_Cnormal_ps.GetDataPtr()); const float *RjT_Ri_Cnormal_ps_ptr = static_cast<const float *>(RjT_Ri_Cnormal_ps.GetDataPtr()); // Association properties const int *cgrid_idx_ps_ptr = static_cast<const int *>(cgrid_idx_ps.GetDataPtr()); const int *cgrid_idx_qs_ptr = static_cast<const int *>(cgrid_idx_qs.GetDataPtr()); const float *cgrid_ratio_ps_ptr = static_cast<const float *>(cgrid_ratio_ps.GetDataPtr()); const float *cgrid_ratio_qs_ptr = static_cast<const float *>(cgrid_ratio_qs.GetDataPtr()); #if defined(__CUDACC__) namespace launcher = core::kernel::cuda_launcher; #else namespace launcher = core::kernel::cpu_launcher; #endif launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t workload_idx) { const float *Ti_Cp = Ti_Cps_ptr + 3 * workload_idx; const float *Tj_Cq = Tj_Cqs_ptr + 3 * workload_idx; const float *Cnormal_p = Cnormal_ps_ptr + 3 * workload_idx; const float *Ri_Cnormal_p = Ri_Cnormal_ps_ptr + 3 * workload_idx; const float *RjTRi_Cnormal_p = RjT_Ri_Cnormal_ps_ptr + 3 * workload_idx; const int *cgrid_idx_p = cgrid_idx_ps_ptr + 8 * workload_idx; const int *cgrid_idx_q = cgrid_idx_qs_ptr + 8 * workload_idx; const float *cgrid_ratio_p = cgrid_ratio_ps_ptr + 8 * workload_idx; const float *cgrid_ratio_q = cgrid_ratio_qs_ptr + 8 * workload_idx; float r = (Ti_Cp[0] - Tj_Cq[0]) * Ri_Cnormal_p[0] + (Ti_Cp[1] - Tj_Cq[1]) * Ri_Cnormal_p[1] + (Ti_Cp[2] - Tj_Cq[2]) * Ri_Cnormal_p[2]; if (abs(r) > threshold) return; // Now we fill in a 60 x 60 sub-matrix: 2 x (6 + 8 x 3) float J[60]; int idx[60]; // Jacobian w.r.t. Ti: 0-6 J[0] = -Tj_Cq[2] * Ri_Cnormal_p[1] + Tj_Cq[1] * Ri_Cnormal_p[2]; J[1] = Tj_Cq[2] * Ri_Cnormal_p[0] - Tj_Cq[0] * Ri_Cnormal_p[2]; J[2] = -Tj_Cq[1] * Ri_Cnormal_p[0] + Tj_Cq[0] * Ri_Cnormal_p[1]; J[3] = Ri_Cnormal_p[0]; J[4] = Ri_Cnormal_p[1]; J[5] = Ri_Cnormal_p[2]; // Jacobian w.r.t. Tj: 6-12 for (int k = 0; k < 6; ++k) { J[k + 6] = -J[k]; idx[k + 0] = 6 * i + k; idx[k + 6] = 6 * j + k; } // Jacobian w.r.t. C over p: 12-36 for (int k = 0; k < 8; ++k) { J[12 + k * 3 + 0] = cgrid_ratio_p[k] * Cnormal_p[0]; J[12 + k * 3 + 1] = cgrid_ratio_p[k] * Cnormal_p[1]; J[12 + k * 3 + 2] = cgrid_ratio_p[k] * Cnormal_p[2]; idx[12 + k * 3 + 0] = 6 * n_frags + cgrid_idx_p[k] * 3 + 0; idx[12 + k * 3 + 1] = 6 * n_frags + cgrid_idx_p[k] * 3 + 1; idx[12 + k * 3 + 2] = 6 * n_frags + cgrid_idx_p[k] * 3 + 2; } // Jacobian w.r.t. C over q: 36-60 for (int k = 0; k < 8; ++k) { J[36 + k * 3 + 0] = -cgrid_ratio_q[k] * RjTRi_Cnormal_p[0]; J[36 + k * 3 + 1] = -cgrid_ratio_q[k] * RjTRi_Cnormal_p[1]; J[36 + k * 3 + 2] = -cgrid_ratio_q[k] * RjTRi_Cnormal_p[2]; idx[36 + k * 3 + 0] = 6 * n_frags + cgrid_idx_q[k] * 3 + 0; idx[36 + k * 3 + 1] = 6 * n_frags + cgrid_idx_q[k] * 3 + 1; idx[36 + k * 3 + 2] = 6 * n_frags + cgrid_idx_q[k] * 3 + 2; } // Not optimized; Switch to reduction if necessary. #if defined(__CUDACC__) for (int ki = 0; ki < 60; ++ki) { for (int kj = 0; kj < 60; ++kj) { float AtA_ij = J[ki] * J[kj]; int ij = idx[ki] * n_vars + idx[kj]; atomicAdd(AtA_ptr + ij, AtA_ij); } float Atb_i = J[ki] * r; atomicAdd(Atb_ptr + idx[ki], Atb_i); } atomicAdd(residual_ptr, r * r); #else #pragma omp critical(FillInSLACAlignmentTermCPU) { for (int ki = 0; ki < 60; ++ki) { for (int kj = 0; kj < 60; ++kj) { AtA_ptr[idx[ki] * n_vars + idx[kj]] += J[ki] * J[kj]; } Atb_ptr[idx[ki]] += J[ki] * r; } *residual_ptr += r * r; } #endif }); } inline OPEN3D_HOST_DEVICE void matmul3x3_3x1(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22, float v0, float v1, float v2, float &o0, float &o1, float &o2) { o0 = m00 * v0 + m01 * v1 + m02 * v2; o1 = m10 * v0 + m11 * v1 + m12 * v2; o2 = m20 * v0 + m21 * v1 + m22 * v2; } inline OPEN3D_HOST_DEVICE void matmul3x3_3x3(float a00, float a01, float a02, float a10, float a11, float a12, float a20, float a21, float a22, float b00, float b01, float b02, float b10, float b11, float b12, float b20, float b21, float b22, float &c00, float &c01, float &c02, float &c10, float &c11, float &c12, float &c20, float &c21, float &c22) { matmul3x3_3x1(a00, a01, a02, a10, a11, a12, a20, a21, a22, b00, b10, b20, c00, c10, c20); matmul3x3_3x1(a00, a01, a02, a10, a11, a12, a20, a21, a22, b01, b11, b21, c01, c11, c21); matmul3x3_3x1(a00, a01, a02, a10, a11, a12, a20, a21, a22, b02, b12, b22, c02, c12, c22); } inline OPEN3D_HOST_DEVICE float det3x3(float m00, float m01, float m02, float m10, float m11, float m12, float m20, float m21, float m22) { return m00 * (m11 * m22 - m12 * m21) - m10 * (m01 * m22 - m02 - m21) + m20 * (m01 * m12 - m02 * m11); } #if defined(__CUDACC__) void FillInSLACRegularizerTermCUDA #else void FillInSLACRegularizerTermCPU #endif (core::Tensor &AtA, core::Tensor &Atb, core::Tensor &residual, const core::Tensor &grid_idx, const core::Tensor &grid_nbs_idx, const core::Tensor &grid_nbs_mask, const core::Tensor &positions_init, const core::Tensor &positions_curr, float weight, int n_frags, int anchor_idx) { int64_t n = grid_idx.GetLength(); int64_t n_vars = Atb.GetLength(); float *AtA_ptr = static_cast<float *>(AtA.GetDataPtr()); float *Atb_ptr = static_cast<float *>(Atb.GetDataPtr()); float *residual_ptr = static_cast<float *>(residual.GetDataPtr()); const int *grid_idx_ptr = static_cast<const int *>(grid_idx.GetDataPtr()); const int *grid_nbs_idx_ptr = static_cast<const int *>(grid_nbs_idx.GetDataPtr()); const bool *grid_nbs_mask_ptr = static_cast<const bool *>(grid_nbs_mask.GetDataPtr()); const float *positions_init_ptr = static_cast<const float *>(positions_init.GetDataPtr()); const float *positions_curr_ptr = static_cast<const float *>(positions_curr.GetDataPtr()); #if defined(__CUDACC__) namespace launcher = core::kernel::cuda_launcher; #else namespace launcher = core::kernel::cpu_launcher; #endif launcher::ParallelFor(n, [=] OPEN3D_DEVICE(int64_t workload_idx) { // Enumerate 6 neighbors int idx_i = grid_idx_ptr[workload_idx]; const int *idx_nbs = grid_nbs_idx_ptr + 6 * workload_idx; const bool *mask_nbs = grid_nbs_mask_ptr + 6 * workload_idx; // Build a 3x3 linear system to compute the local R float cov[3][3] = {{0}}; float U[3][3], V[3][3], S[3]; int cnt = 0; for (int k = 0; k < 6; ++k) { bool mask_k = mask_nbs[k]; if (!mask_k) continue; int idx_k = idx_nbs[k]; // Now build linear systems float diff_ik_init[3] = {positions_init_ptr[idx_i * 3 + 0] - positions_init_ptr[idx_k * 3 + 0], positions_init_ptr[idx_i * 3 + 1] - positions_init_ptr[idx_k * 3 + 1], positions_init_ptr[idx_i * 3 + 2] - positions_init_ptr[idx_k * 3 + 2]}; float diff_ik_curr[3] = {positions_curr_ptr[idx_i * 3 + 0] - positions_curr_ptr[idx_k * 3 + 0], positions_curr_ptr[idx_i * 3 + 1] - positions_curr_ptr[idx_k * 3 + 1], positions_curr_ptr[idx_i * 3 + 2] - positions_curr_ptr[idx_k * 3 + 2]}; // Build linear system by computing XY^T when formulating Y = RX // Y: curr // X: init for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cov[i][j] += diff_ik_init[i] * diff_ik_curr[j]; } } ++cnt; } if (cnt < 3) { return; } // clang-format off svd(cov[0][0], cov[0][1], cov[0][2], cov[1][0], cov[1][1], cov[1][2], cov[2][0], cov[2][1], cov[2][2], U[0][0], U[0][1], U[0][2], U[1][0], U[1][1], U[1][2], U[2][0], U[2][1], U[2][2], S[0], S[1], S[2], V[0][0], V[0][1], V[0][2], V[1][0], V[1][1], V[1][2], V[2][0], V[2][1], V[2][2]); // TODO: det3x3 and matmul3x3 float R[3][3]; // clang-format off matmul3x3_3x3(V[0][0], V[0][1], V[0][2], V[1][0], V[1][1], V[1][2], V[2][0], V[2][1], V[2][2], U[0][0], U[1][0], U[2][0], U[0][1], U[1][1], U[2][1], U[0][2], U[1][2], U[2][2], R[0][0], R[0][1], R[0][2], R[1][0], R[1][1], R[1][2], R[2][0], R[2][1], R[2][2]); float d = det3x3(R[0][0], R[0][1], R[0][2], R[1][0], R[1][1], R[1][2], R[2][0], R[2][1], R[2][2]); // clang-format on if (d < 0) { // clang-format off matmul3x3_3x3(V[0][0], V[0][1], V[0][2], V[1][0], V[1][1], V[1][2], V[2][0], V[2][1], V[2][2], U[0][0], U[1][0], U[2][0], U[0][1], U[1][1], U[2][1], -U[0][2], -U[1][2], -U[2][2], R[0][0], R[0][1], R[0][2], R[1][0], R[1][1], R[1][2], R[2][0], R[2][1], R[2][2]); // clang-format on } // Now we have R, we build Hessian and residuals // But first, we need to anchor a point if (idx_i == anchor_idx) { R[0][0] = R[1][1] = R[2][2] = 1; R[0][1] = R[0][2] = R[1][0] = R[1][2] = R[2][0] = R[2][1] = 0; } for (int k = 0; k < 6; ++k) { bool mask_k = mask_nbs[k]; if (mask_k) { int idx_k = idx_nbs[k]; float diff_ik_init[3] = { positions_init_ptr[idx_i * 3 + 0] - positions_init_ptr[idx_k * 3 + 0], positions_init_ptr[idx_i * 3 + 1] - positions_init_ptr[idx_k * 3 + 1], positions_init_ptr[idx_i * 3 + 2] - positions_init_ptr[idx_k * 3 + 2]}; float diff_ik_curr[3] = { positions_curr_ptr[idx_i * 3 + 0] - positions_curr_ptr[idx_k * 3 + 0], positions_curr_ptr[idx_i * 3 + 1] - positions_curr_ptr[idx_k * 3 + 1], positions_curr_ptr[idx_i * 3 + 2] - positions_curr_ptr[idx_k * 3 + 2]}; float R_diff_ik_curr[3]; // clang-format off matmul3x3_3x1(R[0][0], R[0][1], R[0][2], R[1][0], R[1][1], R[1][2], R[2][0], R[2][1], R[2][2], diff_ik_init[0], diff_ik_init[1], diff_ik_init[2], R_diff_ik_curr[0], R_diff_ik_curr[1], R_diff_ik_curr[2]); // clang-format on float local_r[3]; local_r[0] = diff_ik_curr[0] - R_diff_ik_curr[0]; local_r[1] = diff_ik_curr[1] - R_diff_ik_curr[1]; local_r[2] = diff_ik_curr[2] - R_diff_ik_curr[2]; int offset_idx_i = 3 * idx_i + 6 * n_frags; int offset_idx_k = 3 * idx_k + 6 * n_frags; #if defined(__CUDACC__) // Update residual atomicAdd(residual_ptr, weight * (local_r[0] * local_r[0] + local_r[1] * local_r[1] + local_r[2] * local_r[2])); for (int axis = 0; axis < 3; ++axis) { // Update AtA: 2x2 atomicAdd(&AtA_ptr[(offset_idx_i + axis) * n_vars + offset_idx_i + axis], weight); atomicAdd(&AtA_ptr[(offset_idx_k + axis) * n_vars + offset_idx_k + axis], weight); atomicAdd(&AtA_ptr[(offset_idx_i + axis) * n_vars + offset_idx_k + axis], -weight); atomicAdd(&AtA_ptr[(offset_idx_k + axis) * n_vars + offset_idx_i + axis], -weight); // Update Atb: 2x1 atomicAdd(&Atb_ptr[offset_idx_i + axis], +weight * local_r[axis]); atomicAdd(&Atb_ptr[offset_idx_k + axis], -weight * local_r[axis]); } #else #pragma omp critical(FillInSLACRegularizerTermCPU) { // Update residual *residual_ptr += weight * (local_r[0] * local_r[0] + local_r[1] * local_r[1] + local_r[2] * local_r[2]); for (int axis = 0; axis < 3; ++axis) { // Update AtA: 2x2 AtA_ptr[(offset_idx_i + axis) * n_vars + offset_idx_i + axis] += weight; AtA_ptr[(offset_idx_k + axis) * n_vars + offset_idx_k + axis] += weight; AtA_ptr[(offset_idx_i + axis) * n_vars + offset_idx_k + axis] -= weight; AtA_ptr[(offset_idx_k + axis) * n_vars + offset_idx_i + axis] -= weight; // Update Atb: 2x1 Atb_ptr[offset_idx_i + axis] += weight * local_r[axis]; Atb_ptr[offset_idx_k + axis] -= weight * local_r[axis]; } } #endif } } }); } } // namespace kernel } // namespace pipelines } // namespace t } // namespace open3d
arb_fermidirac.c
/* Based on: https://github.com/fredrik-johansson/arb/blob/master/examples/integrals.c A. Odrzywołek, 2022-02-16, andrzej.odrzywolek@uj.edu.pl Install Arb https://arblib.org/ sudo apt install libflint-arb-dev sudo apt install libflint-arb2 sudo apt install libflint-dev Compile with: gcc arb_fermidirac.c -o arb_fd -lflint -lflint-arb -lm -lfermidirac -lquadmath dfermi200.o fedi_cpc.o -lgfortran */ /* Generalized Fermi–Dirac functions and derivatives: properties and evaluation Published: 1 June 2001 | Version 1 | DOI: 10.17632/57tnc6sby7.1 Contributors: Zhigang Gong, Ladislav Zejda, Werner Däppen, Josep M. Aparicio DOWNLOAD CODE FROM: https://elsevier.digitalcommonsdata.com/datasets/57tnc6sby7/1 Compile instructions: gfortran -c fedi_cpc.for gfortran -c dfermi200.for Copy files fedi_cpc.o, dfermi200.o to test/ subdir */ #include <string.h> #include <acb_calc.h> #include <arb.h> #include <acb_hypgeom.h> //#include "double_interval.h" // Require the most recent Arb, I'm unable to install it A.O. #include <fermidirac.h> #include <quadmath.h> #include <omp.h> double dfermi200_(int *, double *,double *,double *); //Gong GFDI int idx, gong_idx[4][4] = {{0, 2, 5, 9}, {1, 4, 8, -1}, {3, 7, -1, -1}, {6, -1, -1, -1}}; //Gong et. al, Table 1. p. 299, CPC 136 (2001) int main(int argc, char *argv[]) { double fd_quad,fd_double; acb_t fd_arb, fd; arb_t fd_real, rel_err, MachineEpsilon, MaxMachineNumber, MinMachineNumber; int m,n, i,j, sign, counter=0, underflow=0, overflow=0, failed=0, lg2_max; double k, eta, theta, GONG, Arb; //di_t interval; Require the most recent Arb, I'm unable to install it A.O. flint_printf("Computed with arb-%s\n", arb_version); acb_init(fd_arb); acb_init(fd); arb_init(fd_real); arb_init(rel_err); arb_init(MachineEpsilon); arb_one(MachineEpsilon); arb_mul_2exp_si(MachineEpsilon, MachineEpsilon, -52); arb_init(MaxMachineNumber); arb_one(MaxMachineNumber); arb_mul_2exp_si(MaxMachineNumber, MaxMachineNumber, 1024); arb_init(MinMachineNumber); arb_one(MinMachineNumber); arb_mul_2exp_si(MinMachineNumber, MinMachineNumber, -1022); sscanf(argv[1],"%lf",&k); sscanf(argv[2],"%d",&lg2_max); #if 1 for(m=0;m<=3;m++) for(n=0;n<=3;n++) { if(m+n>3) continue; printf("Testing derivative %d%d\n\n",m,n); //#pragma omp parallel for collapse(3) private(idx, eta,theta, fd, fd_real, fd_arb, fd_quad, rel_err, GONG, sign,i,j) shared(lg2_max,m,n) reduction(+ :counter, overflow, underflow, failed) for(sign=-1;sign<=1;sign=sign+2) for(i=-lg2_max;i<=lg2_max;i=i+1) for(j=-lg2_max;j<=lg2_max;j=j+1) { counter++; eta = sign*pow(2,i); theta = pow(2,j); if(!(counter%1024)) printf("Total tested = %d, overflow=%d, underflow=%d, failed=%d\n",counter, overflow, underflow, failed); Ffermi_derivatives_m_n_arb(fd_arb, k, eta, theta, m, n); acb_get_real(fd_real,fd_arb); if( arb_ge(fd_real, MaxMachineNumber) ){ overflow++;continue;} if( arb_le(fd_real, MinMachineNumber) ){ underflow++;continue;} fd_quad = (double) Ffermi_derivatives_m_n_quad((__float128) k, (__float128) eta, (__float128) theta, m, n); //fd_quad = (double) Ffermi_sommerfeld_derivatives_m_n_quad(k, eta, theta, m, n,powq(2.0q,-64.0q),11); //fd_quad = (double) Ffermi_dblexp_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 128*DBL_EPSILON, MAX_REFINE); //fd_double = Ffermi_derivatives_m_n_internal_arb(0.5, sign*pow(2,i), pow(2,j), m, n); //fd_quad = Ffermi_derivatives_m_n(k, eta, theta, m, n); //printf("%e\n", fd_quad/fd_double-1.0); acb_set_d(fd, fd_quad); acb_div(fd, fd, fd_arb, 128); acb_add_si(fd, fd, -1, 128); acb_abs(rel_err, fd, 128); if( arb_ge(rel_err, MachineEpsilon) || (!acb_is_finite(fd_arb)) ) { failed++; printf("\nArb= "); //acb_print(fd_arb);printf("\n"); //acb_printd(fd_arb, 128);printf("\n"); acb_printn(fd_arb, 128, 0);printf("\n"); printf("libfermidirac=%.18e\n", fd_quad); idx = gong_idx[m][n]; GONG = dfermi200_(&idx,&k, &eta, &theta); printf("GONG =%.18e\n",GONG); printf("%d %d\t%d\t",sign,i,j); printf("k=%.1lf eta=%e theta=%e m=%d n=%d\n", k, eta, theta, m, n); printf("Relative error:\t");arb_printn(rel_err, 128, 0); acb_set_d(fd, GONG); acb_div(fd, fd, fd_arb, 128); acb_add_si(fd, fd, -1, 128); acb_abs(rel_err, fd, 128); printf("\nRelative error:\t");arb_printn(rel_err, 128, 0); printf("\n0.5*eta*theta=%e\n", eta*theta*0.5); printf("\n------------------------------------------------------------------------------\n\n"); } } } #endif #if 0 m=3;n=0; printf("Testing derivative %d%d\n\n",m,n); sign=1; k=0.5; theta = pow(2.0,38); for(eta=32.0;eta<=128.0;eta=eta+0.125) { Arb = Ffermi_derivatives_m_n_internal_arb(k, eta, theta, m, n); fd_quad = (double) Ffermi_dblexp_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 8*DBL_EPSILON, MAX_REFINE); fd_double = (double) Ffermi_sommerfeld_derivatives_m_n_quad(k,eta,theta, m, n, (__float128) 8*DBL_EPSILON, MAX_REFINE); //fd_double = (double) Ffermi_derivatives_m_n_quad(k,eta,theta, m, n); idx = gong_idx[m][n]; GONG = dfermi200_(&idx,&k, &eta, &theta); printf("%lf\t%.18e\t%.18e\t%.18e\t%.18e\n",eta,Arb,fd_quad,GONG,fd_double); } #endif acb_clear(fd_arb); acb_clear(fd); arb_clear(fd_real); arb_clear(rel_err); arb_clear(MachineEpsilon); arb_clear(MaxMachineNumber); arb_clear(MinMachineNumber); printf("Finally tested = %d, overflow=%d, underflow=%d, failed=%d\n",counter, overflow, underflow, failed); return 0; }
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2019 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/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *,const MapMode, const RectangleInfo *,const MagickBooleanType,NexusInfo *,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireAlignedMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; register ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory( number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); nexus_info[0]=(NexusInfo *) AcquireQuantumMemory(number_threads, sizeof(**nexus_info)); if (nexus_info[0] == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(nexus_info[0],0,number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) number_threads; i++) { nexus_info[i]=(&nexus_info[0][i]); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % void *AcquirePixelCachePixels(const Image *image,size_t *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *AcquirePixelCachePixels(const Image *image,size_t *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=(size_t) cache_info->length; return(cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict image_nexus; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & WriteMaskChannel) == 0) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=QuantumScale*GetPixelWriteMask(image,p); if (fabs(mask_alpha) >= MagickEpsilon) { for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(MagickOver_((double) p[i],mask_alpha* GetPixelAlpha(image,p),(double) q[i],(double) GetPixelAlpha(image,q))); } SetPixelAlpha(image,GetPixelAlpha(image,p),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (n < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->storage_class == clone_info->storage_class) && (cache_info->colorspace == clone_info->colorspace) && (cache_info->alpha_trait == clone_info->alpha_trait) && (cache_info->channels == clone_info->channels) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->number_channels*cache_info->columns*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(MaxCacheThreads); clone_nexus=AcquirePixelCacheNexus(MaxCacheThreads); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->number_channels*cache_info->columns, clone_info->number_channels*clone_info->columns); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; register ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region,MagickFalse, clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { register const Quantum *magick_restrict p; register Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { register ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; RectangleInfo region; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; region.width=cache_info->columns; region.height=1; region.x=0; region.y=y; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region,MagickFalse, cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; region.width=clone_info->columns; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,&region, MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } cache_nexus=DestroyPixelCacheNexus(cache_nexus,MaxCacheThreads); clone_nexus=DestroyPixelCacheNexus(clone_nexus,MaxCacheThreads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache != (void *) NULL) image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishAlignedMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { register ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) number_threads; i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } nexus_info[0]=(NexusInfo *) RelinquishMagickMemory(nexus_info[0]); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *) image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); } if (cache_info->opencl != (MagickCLCacheInfo) NULL) RetainOpenCLMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=time((time_t *) NULL); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (time((time_t *) NULL)-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { register ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; register Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); register const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the class type of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(cache_info->number_channels*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(cache_info->number_channels*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCacheNexus() method is: % % Quantum *GetVirtualPixelCacheNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; /* Compute the remainder of dividing offset by extent. It returns not only the quotient (tile the offset falls in) but also the positive remainer within that tile such that 0 <= remainder < extent. This method is essentially a ldiv() using a floored modulo division rather than the normal default truncated modulo division. */ modulo.quotient=offset/(ssize_t) extent; if ((offset < 0L) && (modulo.quotient > (ssize_t) (-SSIZE_MAX))) modulo.quotient--; modulo.remainder=(ssize_t) (offset-(double) modulo.quotient*extent); return(modulo); } MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo **magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; RectangleInfo region; register const Quantum *magick_restrict p; register const void *magick_restrict r; register Quantum *magick_restrict q; register ssize_t i, u; register unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,&region, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns) <= (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows) <= (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ s=(unsigned char *) nexus_info->metacontent; virtual_nexus=AcquirePixelCacheNexus(1); (void) memset(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) memset(virtual_metacontent,0,cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, *virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,*virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,*virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,*virtual_nexus); (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels*length; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); virtual_nexus=DestroyPixelCacheNexus(virtual_nexus,1); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the image mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum ApplyPixelCompositeMask(const Quantum p, const MagickRealType alpha,const Quantum q,const MagickRealType beta) { double mask_alpha; if (fabs(alpha-OpaqueAlpha) < MagickEpsilon) return(p); mask_alpha=1.0-QuantumScale*QuantumScale*alpha*beta; mask_alpha=PerceptibleReciprocal(mask_alpha); return(ClampToQuantum(mask_alpha*MagickOver_((double) p,alpha,(double) q,beta))); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickSizeType number_pixels; NexusInfo **magick_restrict image_nexus; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t n; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & CompositeMaskChannel) == 0) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); image_nexus=AcquirePixelCacheNexus(1); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height,image_nexus[0], exception); q=nexus_info->pixels; number_pixels=(MagickSizeType) nexus_info->region.width* nexus_info->region.height; for (n=0; n < (ssize_t) number_pixels; n++) { double mask_alpha; register ssize_t i; if (p == (Quantum *) NULL) break; mask_alpha=(double) GetPixelCompositeMask(image,p); for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyPixelCompositeMask(p[i],mask_alpha,q[i], (MagickRealType) GetPixelAlpha(image,q)); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } image_nexus=DestroyPixelCacheNexus(image_nexus,1); if (n < (ssize_t) number_pixels) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) if (posix_fallocate(cache_info->file,offset+1,extent-offset) != 0) return(MagickFalse); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *hosts, *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if ((AcquireMagickResource(WidthResource,image->columns) == MagickFalse) || (AcquireMagickResource(HeightResource,image->rows) == MagickFalse)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->channels=image->channels; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=cache_info->number_channels*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; } else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length != (MagickSizeType) ((size_t) length)) cache_info->type=DiskCache; else { status=AcquireMagickResource(MapResource,cache_info->length); if (status == MagickFalse) cache_info->type=DiskCache; else if ((cache_info->type != MapCache) && (cache_info->type != MemoryCache)) { cache_info->type=DiskCache; RelinquishMagickResource(MapResource,cache_info->length); } else { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->type=DiskCache; cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } return(status == 0 ? MagickFalse : MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status == 0 ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=DiskCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(SyncImagePixelCache(image,exception)); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->channels=cache_info->channels; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; RectangleInfo region; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ region.x=x; region.y=y; region.width=columns; region.height=rows; pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,&region, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { register MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register ssize_t y; register unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register Quantum *magick_restrict q; register ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t C a c h e A n o n y m o u s M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetCacheAnonymousMemory() resets the anonymous_memory value. % % The format of the ResetCacheAnonymousMemory method is: % % void ResetCacheAnonymousMemory(void) % */ MagickPrivate void ResetCacheAnonymousMemory(void) { cache_anonymous_memory=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels(const CacheInfo *cache_info, % const MapMode mode,const RectangleInfo *region, % const MagickBooleanType buffered,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o region: A pointer to the RectangleInfo structure that defines the % region of this particular cache nexus. % % o buffered: if true, nexus pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MagickSizeType length, NexusInfo *nexus_info,ExceptionInfo *exception) { if (length != (MagickSizeType) ((size_t) length)) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=0; nexus_info->mapped=MagickFalse; if (cache_anonymous_memory <= 0) { nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) length)); if (nexus_info->cache != (Quantum *) NULL) (void) memset(nexus_info->cache,0,(size_t) length); } else { nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) length); if (nexus_info->cache != (Quantum *) NULL) nexus_info->mapped=MagickTrue; } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=length; return(MagickTrue); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (nexus_info->length < CACHE_LINE_SIZE) return; if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE, 0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,1,1); } static Quantum *SetPixelCacheNexusPixels(const CacheInfo *cache_info, const MapMode mode,const RectangleInfo *region, const MagickBooleanType buffered,NexusInfo *nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); (void) memset(&nexus_info->region,0,sizeof(nexus_info->region)); if ((region->width == 0) || (region->height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "NoPixelsDefinedInCache","`%s'",cache_info->filename); return((Quantum *) NULL); } assert(nexus_info->signature == MagickCoreSignature); if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { ssize_t x, y; x=(ssize_t) region->width+region->x-1; y=(ssize_t) region->height+region->y-1; if (((region->x >= 0) && (region->y >= 0) && (y < (ssize_t) cache_info->rows)) && (((region->x == 0) && (region->width == cache_info->columns)) || ((region->height == 1) && (x < (ssize_t) cache_info->columns)))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) region->y*cache_info->columns+region->x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; nexus_info->region=(*region); nexus_info->authentic_pixel_cache=MagickTrue; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ if (((region->x != (ssize_t) nexus_info->region.width) || (region->y != (ssize_t) nexus_info->region.height)) && ((AcquireMagickResource(WidthResource,region->width) == MagickFalse) || (AcquireMagickResource(HeightResource,region->height) == MagickFalse))) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",cache_info->filename); return((Quantum *) NULL); } number_pixels=(MagickSizeType) region->width*region->height; length=MagickMax(number_pixels,cache_info->columns)* cache_info->number_channels*sizeof(*nexus_info->pixels); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; status=MagickTrue; if (nexus_info->cache == (Quantum *) NULL) status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); } if (status == MagickFalse) return((Quantum *) NULL); nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+ cache_info->number_channels*number_pixels); nexus_info->region=(*region); nexus_info->authentic_pixel_cache=cache_info->type == PingCache ? MagickTrue : MagickFalse; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (image->mask_trait != UpdatePixelTrait) { if (((image->channels & WriteMaskChannel) != 0) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (((image->channels & CompositeMaskChannel) != 0) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); } if (nexus_info->authentic_pixel_cache != MagickFalse) { image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (status != MagickFalse) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(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 MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const unsigned char *magick_restrict p; register ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { register unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; register const Quantum *magick_restrict p; register ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { register Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->number_channels*cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
atomic.c
#include <omp.h> int main (void) { int a; #pragma omp parallel { #pragma omp atomic a+=1; } }
Misc.h
//######################################################################## //## Copyright 2019 Da Yan http://www.cs.uab.edu/yanda //## //## 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. //######################################################################## //######################################################################## //## Contributors //## * Wenwen Qu //## * Da Yan //######################################################################## #ifndef __sleuth_misc_h #define __sleuth_misc_h #include "assert.h" #include "../treeminer/Hashtable.h" FreqHT FK; #define ChildrenT map<Element*, vector<Element*> > struct TransBlock{ int st1; int st2; int end1; int end2; bool ins_flag; // whether inside or outside bool f2; TransBlock(int i1, int i2, int e1, int e2, int flag, int _f2): st1(i1), st2(i2), end1(e1), end2(e2), ins_flag(flag), f2(_f2){} }; //check where a element is frequent bool notfrequent(Element &n, int iter) { if(mine_induced && n.isup >= minsup) return false; else if(!mine_induced && n.sup >= minsup) return false; return true; } /*if a tree if canonical, each level of the tree follows certain orders. * cand is the full tree, tpos is pos of root of current rightmost subtree */ bool check_canonical(vector<int> &cand, int tpos) { if (mine_ordered) return true; //only have to check subtrees on rightmost path, with their immediate siblings to the left, and make sure code is smaller or equal bool first; int i, parent = 0, sibling; int scnt = 0; //base condition for stopping recursion, the root has no sibling if (tpos == 0) { return true; } //find the pos of parent and immediate left sibling of tpos under parent first = true; sibling = -1; //not found! for (i = tpos - 1; i >= 0; i--) { if (cand[i] == BranchIt) scnt++; else scnt--; if (first && scnt == 0) { sibling = i; first = false; } if (scnt < 0) { // parent is before all siblings parent = i; break; } } if (sibling == -1) { // not found! return check_canonical(cand, parent); } else { //compare the two subtrees rooted at tpos and sibling int j; for (i = tpos, j = sibling; i < cand.size() && j < tpos; i++, j++) { if (cand[i] > cand[j]) return check_canonical(cand, parent); else if (cand[i] < cand[j]) { return false; } } } return true; } bool lexsmaller(vector<int> &subtree, vector<int> &cand) { int i,j; for (i=0, j=0; i < subtree.size() && j < cand.size();){ if (subtree[i] > cand[j]){ if (cand[j] != BranchIt) return false; else{ while (cand[j] == BranchIt) j++; if (subtree[i] > cand[j]) return false; else if (subtree[i] < cand[j]) return true; else return false; } } else if (subtree[i] < cand[j]){ if (subtree[i] != BranchIt) return true; else{ while(subtree[i] == BranchIt) i++; if (subtree[i] > cand[j]) return false; else if (subtree[i] < cand[j]) return true; else return true; } } else{ i++; j++; } } return false; } /*return a new node to previous prefix pattern. the new node with "val" will appends to the node in "pos" * we also can prune new node if one of new pattern's parent if not frequent. */ Element* test_node(int iter, TreeMinerPattern *eq, int val, int pos) { Element *eqn = NULL; //if noprune, return with a new Eqnode if (prune_type == noprune) { eqn = new Element(val, pos); return eqn; } assert(false); // the pruning logic below does not work for DFS, should be disabled //perform pruning //prune based on frequent subtree vector<int> cand; vector<int> subtree; int hval; int scope, scnt; //form the candidate preifx cand = eq->prefix(); scnt = eq->get_scope(pos, scope); //what is the scope of node.pos while (scnt > scope) { cand.push_back(BranchIt); scnt--; } cand.push_back(val); bool res = true; //check subtrees int omita, omitb; res = true; //omit i-th item (omita) and associated BranchIt (omitb) int i, j, k; for (i = iter - 3; i >= 0; i--) { //find pos for i-th item for (j = 0, k = 0; j < cand.size(); j++) { if (cand[j] != BranchIt) { if (k == i) { omita = j; break; } else k++; } } //find pos for associated BranchIt scnt = 0; for (j++; j < cand.size() && scnt >= 0; j++) { if (cand[j] == BranchIt) scnt--; else scnt++; } if (scnt >= 0) omitb = cand.size(); else omitb = j - 1; hval = 0; subtree.clear(); bool rootless = false; scnt = 0; for (k = 0; k < cand.size() && !rootless; k++) { if (k != omita && k != omitb) { subtree.push_back(cand[k]); if (cand[k] != BranchIt) { hval += cand[k]; scnt++; } else scnt--; if (scnt <= 0) rootless = true; } } //skip a rootless subtree if (!rootless && lexsmaller(subtree, cand)) { res = FK.find(iter - 1, subtree, hval); if (!res) return NULL; //subtree not found! } } if (res) eqn = new Element(val, pos); else eqn = NULL; return eqn; } /* After we generate a new child extension eqnode, update the projected database of the new eqnode. * @l1 : the projected database for pattern A * @l2 : the projected database for pattern B * @ins : the new eqnode * @st1, end1 : the begin and end position in l1 * @st2, end2 : the begin and end position in l2 */ void check_ins(vector<TreeMinerProjTrans> *l1, vector<TreeMinerProjTrans> *l2, Element *ins, // inside int st1, int st2, int en1, int en2, bool f2, vector<TreeMinerProjTrans>* output_tlist) { TreeMinerProjTrans *n1, *n2; ival_type cmpval; bool found_flg = false; // child extension found? bool induced = false; // induced projected instance found for a join output? bool induced_flg = false; // induced projected instance found for the current transaction? int pos1 = st1; //temporary position holder for n1 ival bool next2; //should we go to next n2 ival? // once child find a parent enty, other entries can be skipped int depth; // if depth == 1, (child, parent) is an induced pattern while (st2 < en2) { n1 = &(*l1)[pos1]; n2 = &(*l2)[st2]; next2 = true; //by default we go to next n2 ival cmpval = ival::compare(n1->itscope, n2->itscope); switch (cmpval) { case sup: //n2 was under some n1, then such a extension is valid depth = n2->depth - n1->depth; if (depth >= 1 && n1->path_equal(*n2)) { if (depth == 1 && n1->induced) induced = true; else induced = false; if (!f2) depth = n2->depth; //construct new projected transaction and push it into the projected database of new child if (en1 - st1 > 1 || use_fullpath) { // project parent path into new projected transaction if(output_tlist) output_tlist->emplace_back(n2->tid, n1->parscope, n1->itscope.lb, n2->itscope, depth, induced); else ins->add_list(n2->tid, n1->parscope, n1->itscope.lb, n2->itscope, depth, induced); } else { if(output_tlist) output_tlist->emplace_back(n2->tid, n2->itscope, depth, induced); else ins->add_list(n2->tid, n2->itscope, depth, induced); } if (!count_unique) ins->sup++; found_flg = true; if (induced) induced_flg = true; } next2 = false; break; case before: //check next n1 ival for same n2 ival next2 = false; break; } if (next2 || pos1 + 1 == en1) { //go to next n2 ival pos1 = st1; st2++; } else pos1++; //go to next n1 ival } if (found_flg && count_unique) ins->sup++; if (induced_flg) ins->isup++; } /* After we generate a new cousin extension eqnode, update the projected database of the new eqnode * @l1 : the projected database for pattern A * @l2 : the projected database for pattern B * @ins : the new eqnode * @st1, end1 : the begin and end position in l1 * @st2, end2 : the begin and edn position in l2 */ void check_outs(vector<TreeMinerProjTrans> *l1, vector<TreeMinerProjTrans> *l2, Element *outs, int st1, int st2, int en1, int en2, vector<TreeMinerProjTrans>* output_tlist) { TreeMinerProjTrans *n1, *n2; ival_type cmpval; bool found_flg = false; bool induced, induced_flg = false; bool next2; int pos1 = st1; while (st2 < en2) { n1 = &(*l1)[pos1]; n2 = &(*l2)[st2]; cmpval = ival::compare(n1->itscope, n2->itscope); switch (cmpval) { case sup: break; //if they have no intersect, then valid case before: case after: if (mine_ordered && cmpval == after) break; //n1 is before n2. Check if n1.par is subset of or equal to n2.par if (n1->path_equal(*n2)) { if (n1->induced && n2->induced) induced = true; else induced = false; //construct new projected transaction and push it into the projected database of new child if (en1 - st1 > 1 || use_fullpath) { // project parent path into new projected transaction if(output_tlist) output_tlist->emplace_back(n2->tid, n1->parscope, n1->itscope.lb, n2->itscope, n2->depth, induced); else outs->add_list(n2->tid, n1->parscope, n1->itscope.lb, n2->itscope, n2->depth, induced); } else { if(output_tlist) output_tlist->emplace_back(n2->tid, n2->itscope, n2->depth, induced); else outs->add_list(n2->tid, n2->itscope, n2->depth, induced); } if (!count_unique) outs->sup++; found_flg = true; if (induced) induced_flg = true; } break; case sub: break; } if (pos1 + 1 == en1) { //go to next n2 ival pos1 = st1; st2++; } else pos1++; //go to next n1 ival } if (found_flg && count_unique) outs->sup++; if (induced_flg) outs->isup++; } //do "scope list join" to get "inside" node and "outside" node's projected database, which is mentioned in zaki's sleuth work. //l1 and l2 are two project database to join //f2 means this function is called by getF2() // the new generate projected database after join will store in ins->tlist and outs->tlist void get_intersect(vector<TreeMinerProjTrans> *l1, vector<TreeMinerProjTrans> *l2, Element *ins, Element *outs, bool f2 = false) { //f2 is true only when we compute F2, set to false for Fk TreeMinerProjTrans *n1, *n2; //in Sleuth paper Fig 3 Vertical Format, n1 points to a row of a rectangle vector<TransBlock> tbs; // store all projected transaction ready to join // join the projected instances of the same transaction //i1 and i2 is the position where tid match begins, e1 and e2 is the position where tid match ends. The join operator will do in [i1, e1] and [i2, e2] int i1 = 0, i2 = 0; // int e1, e2; while (i1 < l1->size() && i2 < l2->size()) { // join n1 = &(*l1)[i1]; n2 = &(*l2)[i2]; //look for matching tids if (n1->tid < n2->tid) i1++; else if (n1->tid > n2->tid) i2++; else { //cids match e1 = i1; e2 = i2; //check the cid end positions in it1 and it2 while (e1 < l1->size() && (*l1)[e1].tid == n1->tid) e1++; while (e2 < l2->size() && (*l2)[e2].tid == n2->tid) e2++; //generate projecetd transaction if candidate found if (ins) // child extension //we use + since the join is merge-like if((l1->size() + l2->size()) <= tauDB_omp) check_ins(l1, l2, ins, i1, i2, e1, e2, f2, 0); // in Sleuth paper Fig 3 Vertical Format, each range [i1, e1) denotes the rows for a transaction with some tid else tbs.emplace_back(i1, i2, e1, e2, true, f2); if (outs) // cousin extension //we use + since the join is merge-like if((l1->size() + l2->size()) <= tauDB_omp) check_outs(l1, l2, outs, i1, i2, e1, e2, 0); // in Sleuth paper Fig 3 Vertical Format, each range [i1, e1) denotes the rows for a transaction with some tid else tbs.emplace_back(i1, i2, e1, e2, false, f2); //restore index to end of cids i1 = e1; i2 = e2; } } //we use + since the join is merge-like if((l1->size() + l2->size()) > tauDB_omp){ //do parallel join vector<vector<TreeMinerProjTrans> > ins_tlistOfThread(THREADS); vector<vector<TreeMinerProjTrans> > outs_tlistOfThread(THREADS); #pragma omp parallel for schedule(dynamic, CHUNK) num_threads(THREADS) for(int i = 0; i < tbs.size(); i++){ TransBlock& cur = tbs[i]; int thread_id = omp_get_thread_num(); if(tbs[i].ins_flag) { check_ins(l1, l2, ins, cur.st1, cur.st2, cur.end1, cur.end2, cur.f2, &ins_tlistOfThread[thread_id]); } else { check_outs(l1, l2, outs, cur.st1, cur.st2, cur.end1, cur.end2, &outs_tlistOfThread[thread_id]); } } if(ins){ for(int i = 0; i < THREADS; i++){ vector<TreeMinerProjTrans>& tlist_i = ins_tlistOfThread[i]; if(ins->tlist.empty()) ins->tlist.swap(tlist_i); else{ ins->tlist.insert(ins->tlist.end(), tlist_i.begin(), tlist_i.end()); } } sort(ins->tlist.begin(), ins->tlist.end(), projTrans_cmp); } if(outs) { for(int i = 0; i < THREADS; i++){ vector<TreeMinerProjTrans>& tlist_i = outs_tlistOfThread[i]; if(outs->tlist.empty()) outs->tlist.swap(tlist_i); else{ outs->tlist.insert(outs->tlist.end(), tlist_i.begin(), tlist_i.end()); } } sort(outs->tlist.begin(), outs->tlist.end(), projTrans_cmp); } } } #endif
isotope.c
/* Copyright (C) 2015 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include "isotope.h" #include <stdlib.h> #include "lapack_wrapper.h" #include "phonoc_const.h" #include "phonoc_utils.h" void iso_get_isotope_scattering_strength( double *gamma, const long grid_point, const double *mass_variances, const double *frequencies, const lapack_complex_double *eigenvectors, const long num_grid_points, const long *band_indices, const long num_band, const long num_band0, const double sigma, const double cutoff_frequency) { long i, j, k, l, m; double *e0_r, *e0_i, e1_r, e1_i, a, b, f, *f0, dist, sum_g, sum_g_k; e0_r = (double *)malloc(sizeof(double) * num_band * num_band0); e0_i = (double *)malloc(sizeof(double) * num_band * num_band0); f0 = (double *)malloc(sizeof(double) * num_band0); for (i = 0; i < num_band0; i++) { f0[i] = frequencies[grid_point * num_band + band_indices[i]]; for (j = 0; j < num_band; j++) { e0_r[i * num_band + j] = lapack_complex_double_real( eigenvectors[grid_point * num_band * num_band + j * num_band + band_indices[i]]); e0_i[i * num_band + j] = lapack_complex_double_imag( eigenvectors[grid_point * num_band * num_band + j * num_band + band_indices[i]]); } } for (i = 0; i < num_band0; i++) { gamma[i] = 0; } for (i = 0; i < num_band0; i++) { /* band index0 */ if (f0[i] < cutoff_frequency) { continue; } sum_g = 0; #ifdef _OPENMP #pragma omp parallel for private(k, l, m, f, e1_r, e1_i, a, b, dist, sum_g_k) reduction(+ \ : sum_g) #endif for (j = 0; j < num_grid_points; j++) { sum_g_k = 0; for (k = 0; k < num_band; k++) { /* band index */ f = frequencies[j * num_band + k]; if (f < cutoff_frequency) { continue; } dist = phonoc_gaussian(f - f0[i], sigma); for (l = 0; l < num_band / 3; l++) { /* elements */ a = 0; b = 0; for (m = 0; m < 3; m++) { e1_r = lapack_complex_double_real( eigenvectors[j * num_band * num_band + (l * 3 + m) * num_band + k]); e1_i = lapack_complex_double_imag( eigenvectors[j * num_band * num_band + (l * 3 + m) * num_band + k]); a += (e0_r[i * num_band + l * 3 + m] * e1_r + e0_i[i * num_band + l * 3 + m] * e1_i); b += (e0_i[i * num_band + l * 3 + m] * e1_r - e0_r[i * num_band + l * 3 + m] * e1_i); } sum_g_k += (a * a + b * b) * mass_variances[l] * dist; } } sum_g += sum_g_k; } gamma[i] = sum_g; } for (i = 0; i < num_band0; i++) { /* Frequency unit to ang-freq: *(2pi)**2/(2pi) */ /* Ang-freq to freq unit (for lifetime): /2pi */ /* gamma = 1/2t */ gamma[i] *= M_2PI / 4 * f0[i] * f0[i] / 2; } free(f0); f0 = NULL; free(e0_r); e0_r = NULL; free(e0_i); e0_i = NULL; } void iso_get_thm_isotope_scattering_strength( double *gamma, const long grid_point, const long *ir_grid_points, const long *weights, const double *mass_variances, const double *frequencies, const lapack_complex_double *eigenvectors, const long num_grid_points, const long *band_indices, const long num_band, const long num_band0, const double *integration_weights, const double cutoff_frequency) { long i, j, k, l, m, gp; double *e0_r, *e0_i, *f0, *gamma_ij; double e1_r, e1_i, a, b, f, dist, sum_g_k; e0_r = (double *)malloc(sizeof(double) * num_band * num_band0); e0_i = (double *)malloc(sizeof(double) * num_band * num_band0); f0 = (double *)malloc(sizeof(double) * num_band0); for (i = 0; i < num_band0; i++) { f0[i] = frequencies[grid_point * num_band + band_indices[i]]; for (j = 0; j < num_band; j++) { e0_r[i * num_band + j] = lapack_complex_double_real( eigenvectors[grid_point * num_band * num_band + j * num_band + band_indices[i]]); e0_i[i * num_band + j] = lapack_complex_double_imag( eigenvectors[grid_point * num_band * num_band + j * num_band + band_indices[i]]); } } gamma_ij = (double *)malloc(sizeof(double) * num_grid_points * num_band0); #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < num_grid_points * num_band0; i++) { gamma_ij[i] = 0; } #ifdef _OPENMP #pragma omp parallel for private(j, k, l, m, f, gp, e1_r, e1_i, a, b, dist, \ sum_g_k) #endif for (i = 0; i < num_grid_points; i++) { gp = ir_grid_points[i]; for (j = 0; j < num_band0; j++) { /* band index0 */ if (f0[j] < cutoff_frequency) { continue; } sum_g_k = 0; for (k = 0; k < num_band; k++) { /* band index */ f = frequencies[gp * num_band + k]; if (f < cutoff_frequency) { continue; } dist = integration_weights[gp * num_band0 * num_band + j * num_band + k]; for (l = 0; l < num_band / 3; l++) { /* elements */ a = 0; b = 0; for (m = 0; m < 3; m++) { e1_r = lapack_complex_double_real( eigenvectors[gp * num_band * num_band + (l * 3 + m) * num_band + k]); e1_i = lapack_complex_double_imag( eigenvectors[gp * num_band * num_band + (l * 3 + m) * num_band + k]); a += (e0_r[j * num_band + l * 3 + m] * e1_r + e0_i[j * num_band + l * 3 + m] * e1_i); b += (e0_i[j * num_band + l * 3 + m] * e1_r - e0_r[j * num_band + l * 3 + m] * e1_i); } sum_g_k += (a * a + b * b) * mass_variances[l] * dist; } } gamma_ij[gp * num_band0 + j] = sum_g_k * weights[gp]; } } for (i = 0; i < num_band0; i++) { gamma[i] = 0; } for (i = 0; i < num_grid_points; i++) { gp = ir_grid_points[i]; for (j = 0; j < num_band0; j++) { gamma[j] += gamma_ij[gp * num_band0 + j]; } } for (i = 0; i < num_band0; i++) { /* Frequency unit to ang-freq: *(2pi)**2/(2pi) */ /* Ang-freq to freq unit (for lifetime): /2pi */ /* gamma = 1/2t */ gamma[i] *= M_2PI / 4 * f0[i] * f0[i] / 2; } free(gamma_ij); gamma_ij = NULL; free(f0); f0 = NULL; free(e0_r); e0_r = NULL; free(e0_i); e0_i = NULL; }
SxSpectrum.h
// --------------------------------------------------------------------------- // // The ab-initio based multiscale library // // S / P H I / n X // // Copyright: Max-Planck-Institute for Iron Research // 40237 Duesseldorf, Germany // // Contact: https://sxlib.mpie.de // Authors: see sphinx/AUTHORS // License: see sphinx/LICENSE // // --------------------------------------------------------------------------- #ifndef _SX_SPECTRUM_H_ #define _SX_SPECTRUM_H_ #include <SxVector.h> #include <SxDFT.h> /** \brief Gaussian broadened spectra \b SxClass = S/PHI/nX ... This class provides utilities to create a spectrum from a set of peaks. \author Christoph Freysoldt */ class SX_EXPORT_DFT SxSpectrum { public: /// Number of points per Gauss peak int nPerPeak; /** The spectra, after computation : (iE, iSpec) This contains the spectra. */ SxVector<Double> spectra; /// Energy scale SxVector<Double> energies; /// Empty constructor SxSpectrum (); /// Destructor ~SxSpectrum () { /* empty */} /** \brief Sets the target diffusion constant. \param D target diffusion constant, 0 < D << 1 \note There is a reasonable default, so this is mainly for debugging purposes. It must be called before the #set routine */ void setDiffusion (double D); /** Set up the energy range and create new spectra. \note Only this routine considers nPerPeak and diffusion, so any changes afterwards have no effect. */ void set(double eMin, double eMax, double broadening, int nSpectra = -1); /// Set number of spectra void resize (int nSpectra); /// Get number of spectra int getNSpectra () const { return computed ? (int)spectra.nCols () : (int)spectra.nRows (); } /** Add a peak */ void addPeak (double ePeak, double weight); /** Add a peak to one of the spectrums */ inline void addPeak (double ePeak, double weight, int iSpectrum); /** Add a peak to each spectrum (with different weights) */ void addPeak (double ePeak, const SxVector<Double> &weights); /** Compute spectra from peaks by diffusion. The addPeak function adds only delta peaks to the spectrum. In this function, these are broadened by a simulated diffusion process, which gives a Gaussian broadening. */ void compute (); /// Print spectra to file void fprint (FILE *fp); /// Get number of energy points int getNPoints () const { return nPoints; } private: /// Compute must be called only once bool computed; /// Lower energy boundary double enMin; /// Energgy spacing double dE; /// Gaussian broadening double broad; /** \brief Diffusion constant The Gauss peaks are computed by letting the delta peaks diffuse. This constant must be lower than 1, it is set to a reasonable default 0.1 . */ double diffusion; /// Number of points in spectrum int nPoints; /// Number of time steps int nTime; }; void SxSpectrum::addPeak (double ePeak, double weight, int iSpectrum) { SX_CHECK (! computed); SX_CHECK (iSpectrum >= 0 && iSpectrum < getNSpectra (), iSpectrum, getNSpectra ()); int pos = int(ceil((ePeak - enMin)/dE)); if (pos < 1 || pos >= nPoints) return; // outside energy scale // distribute over closest energy grid points double dW = (energies(pos) - ePeak) / dE; #ifdef USE_OPENMP #pragma omp atomic update #endif spectra(iSpectrum, pos) += weight * (1. - dW) / dE; #ifdef USE_OPENMP #pragma omp atomic update #endif spectra(iSpectrum, pos-1) += weight * dW / dE; } #endif /* _SX__H_ */
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] = 16; tile_size[1] = 16; tile_size[2] = 32; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } 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,2);t1++) { lbp=max(ceild(t1,2),ceild(4*t1-Nt+2,4)); ubp=min(floord(4*Nt+Nz-9,16),floord(8*t1+Nz+2,16)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(0,ceild(t1-3,4)),ceild(16*t2-Nz-19,32));t3<=min(min(min(floord(4*Nt+Ny-9,32),floord(8*t1+Ny+7,32)),floord(16*t2+Ny+3,32)),floord(16*t1-16*t2+Nz+Ny+5,32));t3++) { for (t4=max(max(max(0,ceild(t1-63,64)),ceild(16*t2-Nz-499,512)),ceild(32*t3-Ny-499,512));t4<=min(min(min(min(floord(4*Nt+Nx-9,512),floord(8*t1+Nx+7,512)),floord(16*t2+Nx+3,512)),floord(32*t3+Nx+19,512)),floord(16*t1-16*t2+Nz+Nx+5,512));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(32*t3-Ny+5,4)),ceild(512*t4-Nx+5,4)),2*t1),4*t1-4*t2+1);t5<=min(min(min(min(min(floord(16*t1-16*t2+Nz+10,4),Nt-1),2*t1+3),4*t2+2),8*t3+6),128*t4+126);t5++) { for (t6=max(max(16*t2,4*t5+4),-16*t1+16*t2+8*t5-15);t6<=min(min(16*t2+15,-16*t1+16*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(32*t3,4*t5+4);t7<=min(32*t3+31,4*t5+Ny-5);t7++) { lbv=max(512*t4,4*t5+4); ubv=min(512*t4+511,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((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; }
csr_matmultivec.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "csr_multimatvec.h" #include "seq_mv.h" #include "seq_multivector.h" /*-------------------------------------------------------------------------- * hypre_CSRMatrixMultiMatvec *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatMultivec(HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Multivector *x, HYPRE_Complex beta, hypre_Multivector *y) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_MultivectorData(x); HYPRE_Complex *y_data = hypre_MultivectorData(y); HYPRE_Int x_size = hypre_MultivectorSize(x); HYPRE_Int y_size = hypre_MultivectorSize(y); HYPRE_Int num_vectors = hypre_MultivectorNumVectors(x); HYPRE_Int *x_active_ind= x->active_indices; HYPRE_Int *y_active_ind= y->active_indices; HYPRE_Int num_active_vectors = x->num_active_vectors; HYPRE_Int i, j, jj, m, ierr = 0, optimize; HYPRE_Complex temp, tempx, xpar=0.7, *xptr, *yptr; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert(num_active_vectors == y->num_active_vectors); if (num_cols != x_size) ierr = 1; if (num_rows != y_size) ierr = 2; if (num_cols != x_size && num_rows != y_size) ierr = 3; optimize = 0; if (num_active_vectors == num_vectors && num_vectors == y->num_vectors) optimize = 1; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ if ( num_vectors==1 ) { for (i = 0; i < num_rows; i++) { temp = y_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] = temp; } } else { if (optimize == 0) { for (i = 0; i < num_rows; i++) { for (j=0; j<num_active_vectors; ++j) { xptr = x_data[x_active_ind[j]*x_size]; temp = y_data[y_active_ind[j]*y_size+i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * xptr[A_j[jj]]; y_data[y_active_ind[j]*y_size+i] = temp; } } } else { for (i = 0; i < num_rows; i++) { for (j=0; j<num_vectors; ++j) { xptr = x_data[j*x_size]; temp = y_data[j*y_size+i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * xptr[A_j[jj]]; y_data[j*y_size+i] = temp; } } /* different version for (j=0; j<num_vectors; ++j) { xptr = x_data[j*x_size]; for (i = 0; i < num_rows; i++) { temp = y_data[j*y_size+i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * xptr[A_j[jj]]; y_data[j*y_size+i] = temp; } } */ } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= alpha; } return ierr; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMultiMatvecT * * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatMultivecT(HYPRE_Complex alpha, hypre_CSRMatrix *A, hypre_Multivector *x, HYPRE_Complex beta, hypre_Multivector *y) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Complex *x_data = hypre_MultivectorData(x); HYPRE_Complex *y_data = hypre_MultivectorData(y); HYPRE_Int x_size = hypre_MultivectorSize(x); HYPRE_Int y_size = hypre_MultivectorSize(y); HYPRE_Int num_vectors = hypre_MultivectorNumVectors(x); HYPRE_Int *x_active_ind= x->active_indices; HYPRE_Int *y_active_ind= y->active_indices; HYPRE_Int num_active_vectors = x->num_active_vectors; HYPRE_Complex temp; HYPRE_Int i, jv, jj, size, ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert(num_active_vectors == y->num_active_vectors); if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ if ( num_vectors==1 ) { for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) y_data[A_j[jj]] += A_data[jj] * x_data[i]; } } else { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) y_data[A_j[jj]+jv*y_size] += A_data[jj] * x_data[i+jv*x_size]; } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= alpha; } return ierr; }
matrixop.c
/* * Code for matrix functions in Dymola * * Copyright (C) 1997-2001 Dynasim AB. * All rights reserved. * * Author: Hans Olsson Dynasim AB, 1999 * Version: 1.2, 1999-07-16*/ /* */ #ifndef MATRIX_OP_C #define MATRIX_OP_C #if defined(_MSC_VER) #if (!DymolaGlobalOptimizations_) || (DymolaGlobalOptimizations_ == 2) #pragma optimize( "g", on ) #endif #endif #if (!defined(LIBDSDLL_EXPORTS)) || defined(DYMOSIM_DLL_EXPORTS) #include "matrixop1.h" #include "localeless.h" /* needed for at least sprintfC */ #include <stddef.h> #include <limits.h> #include <float.h> #include <string.h> struct TaggedIndexStack { enum Subtag tag; union { Integer index; Integer range[3]; IntegerArray vector; } u; }; #undef Assert #define Assert(b,x) if (!(b)) AssertModelicaF(b,#b,x) DYMOLA_STATIC struct TaggedIndexStack*HandleVaList(va_list ap, struct TaggedIndexStack*VA_handler,int num_VA_handler) { int i; struct TaggedIndexStack*VA_handler_p=VA_handler; for(i=0;i<num_VA_handler;++i,++VA_handler_p) { enum Subtag tag=va_arg(ap,int); Assert(i+4<num_VA_handler,"Out of memory for va_list"); VA_handler_p->tag=(enum Subtag)(tag); if (tag==EndMark) break; switch(tag) { case Colon: break; case Range:case RangeRange: { Integer start,stop,stride=1; start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); VA_handler_p->u.range[0]=start; VA_handler_p->u.range[1]=stride; VA_handler_p->u.range[2]=stop; } break; case Index: { VA_handler_p->u.index=va_arg(ap,Integer); break; } case Vector: { VA_handler_p->u.vector=va_arg(ap,IntegerArray); break; } case EndMark: { /* shouldn't happen*/ break; } } } return VA_handler; } /* Buffers and keeping track of them by Mark and Release */ /* The idea is that each function has two marks: RealArray f(...) { RealArray res=RealTemporaryMatrix(...); MarkObject returnMark=PushMark(); RealArray temp=RealTemporaryMatrix(...); ... MarkObject functionMark=PushMark(); ... for(...) { ... Release(); // Destroy everything except local variables and return-value { RealArray v_=RealScalarArray(...); Integer index_; MarkObject for_mark=PushMark(); for(index_=0;index_<v_.dims[0];index_++) { v=v_.data[index_]; ... Release(); }; PopMark(for_mark); } ... Release(); ... PopMark(returnMark); // Destroy everything except the return-value return res; } */ DYMOLA_STATIC MarkObject currentMarkNon={{RealbufferNon,IntegerbufferNon,SizebufferNon,StringbufferNon},{RealbufferNon,IntegerbufferNon,SizebufferNon,StringbufferNon}}; DYMOLA_STATIC char*startstringmarkNon=simplestringNon; #if defined(DYN_MULTINSTANCE) #define startMark (DYN_GetThreadData()->m_start) #define currentMark (DYN_GetThreadData()->m_current) #define stringmark (DYN_GetThreadData()->m_stringmark) #define startstringmark (DYN_GetThreadData()->m_startstringmark) #define EndRealbuffer (DYN_GetThreadData()->m_endreal) #define EndIntegerbuffer (DYN_GetThreadData()->m_endinteger) #define EndSizebuffer (DYN_GetThreadData()->m_endsize) #define EndStringbuffer (DYN_GetThreadData()->m_endstring) #define Endsimplestring (DYN_GetThreadData()->m_endsimplestring) DYMOLA_STATIC void EnsureMarkInitializedFunction() { struct DYN_ThreadData*threadData=0; threadData=DYN_GetThreadData(); if (threadData && 0==threadData->m_endreal) { const int numReal= #ifndef DYNREALBUFFER 500000 #else DYNREALBUFFER #endif ; const int numInteger = #ifndef DYNINTEGERBUFFER 50000 #else DYNINTEGERBUFFER #endif ; const int numString = #ifndef DYNSTRINGBUFFER 10000 #else DYNSTRINGBUFFER #endif ; threadData->m_current.place.Realbuffer=(Real*)calloc(numReal,sizeof(Real)); threadData->m_endreal=threadData->m_current.place.Realbuffer+numReal; threadData->m_current.place.Integerbuffer=(Integer*)calloc(numInteger,sizeof(Integer)); threadData->m_endinteger=threadData->m_current.place.Integerbuffer+ numInteger; threadData->m_current.place.Sizebuffer=(SizeType*)calloc(numInteger,sizeof(SizeType)); threadData->m_endsize=threadData->m_current.place.Sizebuffer+ numInteger; threadData->m_current.place.Stringbuffer=(String*)calloc(numString,sizeof(String)); threadData->m_endstring=threadData->m_current.place.Stringbuffer+ numString; threadData->m_current.mark=threadData->m_current.place; threadData->m_start=threadData->m_current; threadData->m_stringmark=threadData->m_startstringmark=calloc(numString,1); threadData->m_endsimplestring=threadData->m_stringmark+ numString; } } DYMOLA_STATIC void EnsureMarkFree(struct DYN_ThreadData*threadData) { if (threadData && 0!=threadData->m_endreal) { free(threadData->m_start.place.Realbuffer); free(threadData->m_start.place.Integerbuffer); free(threadData->m_start.place.Sizebuffer); free(threadData->m_start.place.Stringbuffer); free((void*)threadData->m_startstringmark); threadData->m_start.place.Realbuffer=0; threadData->m_endreal=0; threadData->m_start.place.Integerbuffer=0; threadData->m_endinteger=0; threadData->m_start.place.Sizebuffer=0; threadData->m_endsize=0; threadData->m_start.place.Stringbuffer=0; threadData->m_endstring=0; threadData->m_start.mark=threadData->m_start.place; threadData->m_current=threadData->m_start; threadData->m_stringmark=threadData->m_startstringmark=0; threadData->m_endsimplestring=0; } } DYMOLA_STATIC void EnsureMarkFree2() { EnsureMarkFree(DYN_GetThreadData()); } #define EnsureMarkInitialized() if (EndRealbuffer==0) EnsureMarkInitializedFunction(); #else DYMOLA_STATIC MarkObject startMark={{Realbuffer,Integerbuffer,Sizebuffer,Stringbuffer},{Realbuffer,Integerbuffer,Sizebuffer,Stringbuffer}}; #if (defined(_OPENMP) && !defined(DISABLE_DYMOLA_OPENMP)) #pragma omp threadprivate(startMark) #endif DYMOLA_STATIC MarkObject currentMark={{Realbuffer,Integerbuffer,Sizebuffer,Stringbuffer},{Realbuffer,Integerbuffer,Sizebuffer,Stringbuffer}}; #if (defined(_OPENMP) && !defined(DISABLE_DYMOLA_OPENMP)) #pragma omp threadprivate(currentMark) #endif extern char simplestring[]; DYMOLA_STATIC char*stringmark=simplestring; #if (defined(_OPENMP) && !defined(DISABLE_DYMOLA_OPENMP)) #pragma omp threadprivate(stringmark) #endif DYMOLA_STATIC char*startstringmark=simplestring; #if (defined(_OPENMP) && !defined(DISABLE_DYMOLA_OPENMP)) #pragma omp threadprivate(startstringmark) #endif #if (defined(_OPENMP) && !defined(DISABLE_DYMOLA_OPENMP)) #include <omp.h> DYMOLA_STATIC void EnsureMarkInitializedFunction() { int i=omp_get_thread_num(); int n=0; int num; if (0==n) { n=omp_get_max_threads(); if (n<omp_get_num_procs()) n=omp_get_num_procs(); if (n<omp_get_num_threads()) n=omp_get_num_threads(); } num=sizeof(Realbuffer)/sizeof(*Realbuffer); currentMark.place.Realbuffer=Realbuffer+(i*num)/n; EndRealbuffer=Realbuffer+((i+1)*num)/n; num=sizeof(Integerbuffer)/sizeof(*Integerbuffer); currentMark.place.Integerbuffer=Integerbuffer+(i*num)/n; EndIntegerbuffer=Integerbuffer+((i+1)*num)/n; num=sizeof(Sizebuffer)/sizeof(*Sizebuffer); currentMark.place.Sizebuffer=Sizebuffer+(i*num)/n; EndSizebuffer=Sizebuffer+((i+1)*num)/n; num=sizeof(Stringbuffer)/sizeof(*Stringbuffer); currentMark.place.Stringbuffer=Stringbuffer+(i*num)/n; EndStringbuffer=Stringbuffer+((i+1)*num)/n; currentMark.mark=currentMark.place; startMark=currentMark; num=sizeof(simplestring)/sizeof(*simplestring); stringmark=startstringmark=simplestring+(i*num)/n; Endsimplestring=simplestring+((i+1)*num)/n; } #define EnsureMarkInitialized() if (EndRealbuffer==0) EnsureMarkInitializedFunction(); #else #define EnsureMarkInitialized() #endif #endif DYMOLA_STATIC MarkObject PushMark(void) { MarkObject oldMark; EnsureMarkInitialized(); oldMark=currentMark; currentMark.mark=currentMark.place; return oldMark; } DYMOLA_STATIC void RePushMark(MarkObject*oldMark) { MarkObject newMark; EnsureMarkInitialized(); newMark=PushMark(); if (oldMark) oldMark->place=newMark.place; } /* Release: used after each matrix assignment in the function */ DYMOLA_STATIC void Release() {EnsureMarkInitialized();currentMark.place=currentMark.mark;} /* At the end of the function */ DYMOLA_STATIC void PopMark(MarkObject oldMark) {EnsureMarkInitialized();currentMark=oldMark;} /* Raw allocation of r temporaries and return a pointer to the start*/ DYMOLA_STATIC Real *RealTemp(SizeType r) { Real *d=0; EnsureMarkInitialized(); d=currentMark.place.Realbuffer; currentMark.place.Realbuffer+=r; Assert(currentMark.place.Realbuffer<EndRealbuffer,"Out of memory for reals\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can change the memory size by setting the variable Advanced.RealBufferSize."); return d; } DYMOLA_STATIC Integer *IntegerTemp(SizeType r) { Integer *i=0; EnsureMarkInitialized(); i=currentMark.place.Integerbuffer; currentMark.place.Integerbuffer+=r; Assert(currentMark.place.Integerbuffer<EndIntegerbuffer,"Out of memory for integers\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Integerbuffer' in dymola/source/matrixop.h."); return i; } DYMOLA_STATIC SizeType *SizeTemp(SizeType r) { SizeType *s=0; EnsureMarkInitialized(); s=currentMark.place.Sizebuffer; currentMark.place.Sizebuffer+=r; Assert(currentMark.place.Sizebuffer<EndSizebuffer,"Out of memory for array dimensions\nIt could due to too many matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Sizebuffer' in dymola/source/matrixop.h."); return s; } DYMOLA_STATIC String * StringTemp(SizeType r) { String *s=0; EnsureMarkInitialized(); s=currentMark.place.Stringbuffer; currentMark.place.Stringbuffer+=r; Assert(currentMark.place.Stringbuffer<EndStringbuffer,"Out of memory for strings\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Stringbuffer' in dymola/source/matrixop.h."); return s; } DYMOLA_STATIC Real *RealNonTemp(SizeType r) { Real *d=0; d=currentMarkNon.place.Realbuffer; currentMarkNon.place.Realbuffer+=r; Assert(currentMarkNon.place.Realbuffer<EndRealbufferNon,"Out of memory for reals\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can change the memory size by setting the variable Advanced.RealBufferSize."); return d; } DYMOLA_STATIC Integer *IntegerNonTemp(SizeType r) { Integer *i=0; i=currentMarkNon.place.Integerbuffer; currentMarkNon.place.Integerbuffer+=r; Assert(currentMarkNon.place.Integerbuffer<EndIntegerbufferNon,"Out of memory for integers\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Integerbuffer' in dymola/source/matrixop.h."); return i; } DYMOLA_STATIC SizeType *SizeNonTemp(SizeType r) { SizeType *s=0; s=currentMarkNon.place.Sizebuffer; currentMarkNon.place.Sizebuffer+=r; Assert(currentMarkNon.place.Sizebuffer<EndSizebufferNon,"Out of memory for array dimensions\nIt could due to too many matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Sizebuffer' in dymola/source/matrixop.h."); return s; } DYMOLA_STATIC String * StringNonTemp(SizeType r) { String *s=0; s=currentMarkNon.place.Stringbuffer; currentMarkNon.place.Stringbuffer+=r; Assert(currentMarkNon.place.Stringbuffer<EndStringbufferNon,"Out of memory for strings\nIt could due to too large matrices, infinite recursion, or uninitialized variables.\nYou can increase the size of 'Stringbuffer' in dymola/source/matrixop.h."); return s; } /* Helper to find index of element */ DYMOLA_STATIC SizeType FindIndex(SizeType ndims,SizeType*dims,va_list ap) { SizeType i,index; index=0; for(i=0;i<ndims;i++) { SizeType j=va_arg(ap,SizeType); SizeType dim=dims[i]; Assert((j>=1)&&(j<=dim),"Index out of bounds"); index=index*dim+(j-1); } return index; } /* Start of common routines */ /* Test for size compatibility, used in assertions */ DYMOLA_STATIC Integer RealMatchingSizes(const RealArray a,const RealArray b) { SizeType i; if (a.ndims!=b.ndims) return 0; for(i=0;i<a.ndims;i++) {if(a.dims[i]!=b.dims[i]) return 0;} return 1; } /* Return total number of elements */ DYMOLA_STATIC SizeType CommonNrElements(SizeType ndims, SizeType* dims) { SizeType prodsize = 1; SizeType i; for (i = 0; i<ndims; i++) prodsize *= dims[i]; return prodsize; } /* Return total number of elements */ DYMOLA_STATIC SizeType RealNrElements(const RealArray a) { SizeType prodsize=1; SizeType i; for(i=0;i<a.ndims;i++) prodsize*=a.dims[i]; return prodsize; } /* Create Array-temporaries given the dimensions */ /* Internal: Use an existing va_list */ DYMOLA_STATIC RealArray RealVaTemporarySize(SizeType ndims,va_list ap) { RealArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC RealArray RealVaTemporary(SizeType ndims,va_list ap) { RealArray temp=RealVaTemporarySize(ndims,ap); temp.data=RealTemp(RealNrElements(temp)); return temp; } DYMOLA_STATIC RealArray RealVaNonTemporarySize(SizeType ndims,va_list ap) { RealArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeNonTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC RealArray RealVaNonTemporary(SizeType ndims,va_list ap) { RealArray temp=RealVaNonTemporarySize(ndims,ap); temp.data=RealNonTemp(RealNrElements(temp)); return temp; } DYMOLA_STATIC IntegerArray IntegerVaNonTemporarySize(SizeType ndims,va_list ap) { IntegerArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeNonTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC IntegerArray IntegerVaNonTemporary(SizeType ndims,va_list ap) { IntegerArray temp=IntegerVaNonTemporarySize(ndims,ap); temp.data=IntegerNonTemp(IntegerNrElements(temp)); return temp; } DYMOLA_STATIC StringArray StringVaNonTemporarySize(SizeType ndims,va_list ap) { StringArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeNonTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC StringArray StringVaNonTemporary(SizeType ndims,va_list ap) { StringArray temp=StringVaNonTemporarySize(ndims,ap); temp.data=StringNonTemp(StringNrElements(temp)); return temp; } /* Construct a temporary of the same size as a */ DYMOLA_STATIC RealArray RealMatch(const RealArray a) { RealArray temp; SizeType i; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;i++) temp.dims[i]=a.dims[i]; temp.data=RealTemp(RealNrElements(a)); return temp; } /* Construct array from sizes, using variable number of arguments */ DYMOLA_STATIC RealArray RealTemporary(SizeType ndims,...) { RealArray temp; va_list ap; va_start(ap,ndims); temp=RealVaTemporary(ndims,ap); va_end(ap); return temp; } /* Construct array from sizes, using variable number of arguments */ DYMOLA_STATIC RealArray RealNonTemporary(SizeType ndims,...) { RealArray temp; va_list ap; va_start(ap,ndims); temp=RealVaNonTemporary(ndims,ap); va_end(ap); return temp; } DYMOLA_STATIC IntegerArray IntegerNonTemporary(SizeType ndims,...) { IntegerArray temp; va_list ap; va_start(ap,ndims); temp=IntegerVaNonTemporary(ndims,ap); va_end(ap); return temp; } DYMOLA_STATIC StringArray StringNonTemporary(SizeType ndims,...) { StringArray temp; va_list ap; va_start(ap,ndims); temp=StringVaNonTemporary(ndims,ap); va_end(ap); return temp; } /* Special cases for vectors and matrices (most often used) */ DYMOLA_STATIC RealArray RealTemporaryMatrix(SizeType r,SizeType c) { RealArray temp; temp.ndims=2; temp.dims=SizeTemp(2); temp.dims[0]=r;temp.dims[1]=c; temp.data=RealTemp(r*c); return temp; } DYMOLA_STATIC RealArray RealTemporaryVector(SizeType r) { RealArray temp; temp.ndims=1; temp.dims=SizeTemp(1); temp.dims[0]=r; temp.data=RealTemp(r); return temp; } /* Assignment */ DYMOLA_STATIC void RealAssign(RealArray a,const RealArray b) { SizeType prodsize=RealNrElements(a); SizeType i; Assert(RealMatchingSizes(a,b),"Array dimensions did not match"); for(i=0;i<prodsize;i++) a.data[i]=b.data[i]; } /* Indexing to set/get elements */ DYMOLA_STATIC Real RealElement(const RealArray a,...) { SizeType index; va_list ap; va_start(ap,a); if (a.ndims == 1) { SizeType j = va_arg(ap, SizeType); Assert((j >= 1) && (j <= a.dims[0]), "Index out of bounds"); index = j - 1; } else { index = FindIndex(a.ndims, a.dims, ap); } va_end(ap); return a.data[index]; } /* Sizes */ DYMOLA_STATIC Integer RealSize(const RealArray a,SizeType i) { Assert((i>=1)&&(i<=a.ndims),"Size must be between 1 and ndims of array"); return a.dims[i-1]; } DYMOLA_STATIC IntegerArray RealSizes(const RealArray a) { IntegerArray res; Integer i; res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=a.ndims; res.data=IntegerTemp(a.ndims); for(i=0;i<a.ndims;i++) res.data[i]=a.dims[i]; return res; } /* Set element, note that val is prior to the index list. */ DYMOLA_STATIC void SetRealElement(Real val,RealArray a,...) { SizeType index; va_list ap; va_start(ap,a); index=FindIndex(a.ndims,a.dims,ap); a.data[index]=val; va_end(ap); } /* For debug write out */ DYMOLA_STATIC void RealWrite(const RealArray a) { SizeType i; DymosimMessageInt("Dims: ",a.ndims); for(i=0;i<a.ndims;i++) DymosimMessageInt(" ",a.dims[i]); for(i=0;i<RealNrElements(a);i++) DymosimMessageMatrixElement("",i,1,a.data[i]); } /* Construct Arrays from other arrays */ DYMOLA_STATIC RealArray RealArrayArray(SizeType narg,RealArray first,...) { RealArray res; SizeType i,j,prodsize; va_list ap; res.ndims=first.ndims+1; res.dims=SizeTemp(res.ndims); res.dims[0]=narg; for(i=1;i<res.ndims;i++) res.dims[i]=first.dims[i-1]; prodsize=RealNrElements(first); res.data=RealTemp(prodsize*narg); va_start(ap,first); for(i=0;i<narg;i++) { RealArray next; next=(i!=0)?va_arg(ap,RealArray):first; Assert(RealMatchingSizes(first,next),"Arrays in array must be of equal sizes"); for(j=0;j<prodsize;j++) res.data[i*prodsize+j]=next.data[j]; } va_end(ap); return res; } /* Construct arrays from scalars */ DYMOLA_STATIC RealArray RealScalarArray(SizeType narg,...) { RealArray res; SizeType i; va_list ap; res=RealTemporaryVector(narg); va_start(ap,narg); for(i=0;i<narg;i++) { res.data[i]=va_arg(ap,Real); } va_end(ap); return res; } /* Get/Put of submatrices, i.e. a[i,:,v,1:4] */ /* Actual get of a submatrix */ DYMOLA_STATIC void RealFromSub(RealArray to,SizeType to_offset,SizeType to_dim, const RealArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) RealFromSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<to_newdim;i++) RealFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+(start+stride*i-1),from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; RealFromSub(to,to_offset,to_dim, from,from_offset*from.dims[from_dim]+i-1,from_dim+1,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) RealFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+v.data[i]-1,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; Real *to_p=to.data+to_offset; Real *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Concatenate along dimensions 'along' (1..ndims) and given nargs arguments */ DYMOLA_STATIC RealArray RealCat(SizeType along,SizeType nargs,RealArray first,...) { RealArray res; va_list ap; SizeType i,j; res.ndims=first.ndims; res.dims=SizeTemp(res.ndims); along--; /* Adapt to C usage */ { /* Pass 1: determine size of output */ for(j=0;j<first.ndims;j++) res.dims[j]=first.dims[j]; /* Starting values */ va_start(ap,first); for(i=1;i<nargs;i++) { RealArray a; a=va_arg(ap,RealArray); Assert(a.ndims==first.ndims,"Number of dimensions must match for cat"); #ifndef NDEBUG for(j=0;j<a.ndims;j++) if (j!=along) {Assert(first.dims[j]==a.dims[j],"Sizes must match for cat");} #endif res.dims[along]+=a.dims[along]; } va_end(ap); } res.data=RealTemp(CommonNrElements(res.ndims, res.dims)); { /* Pass 2: copy data */ SizeType presize=1; /* Blocks */ SizeType trailingsize=1; /* Elements in each block */ SizeType marker=0; /* How far are in res along dimension along */ for(i=0;i<along;i++) presize*=res.dims[i]; for(i=along+1;i<res.ndims;i++) trailingsize*=res.dims[i]; va_start(ap,first); for(i=0;i<nargs;i++) { SizeType pre,current,trailing; RealArray a; if (i!=0) a=va_arg(ap,RealArray); else a=first; for(pre=0;pre<presize;pre++) for(current=0;current<a.dims[along];current++) for(trailing=0;trailing<trailingsize;trailing++) res.data[(pre*res.dims[along]+(current+marker))*trailingsize+trailing]= a.data[(pre*a.dims[along]+current)*trailingsize+trailing]; marker+=a.dims[along]; } va_end(ap); } return res; } /* The helper in Modelica */ DYMOLA_STATIC RealArray RealPromote(const RealArray a,SizeType n) { RealArray res; SizeType i; Assert(n>=a.ndims,"Promote cannot decrease number of dimensions"); res.ndims=n; res.data=a.data; /* No need to copy */ res.dims=SizeTemp(n); for(i=0;i<a.ndims;i++) res.dims[i]=a.dims[i]; for(i=a.ndims;i<n;i++) res.dims[i]=1; return res; } DYMOLA_STATIC RealArray RealPromoteScalar(const Real x,SizeType n) { RealArray res; Integer i; res.ndims=n; res.data=RealTemp(1); res.data[0]=x; res.dims=SizeTemp(n); for(i=0;i<n;i++) res.dims[i]=1; return res; } /* Actual put of submatrix */ DYMOLA_STATIC void RealToSub(RealArray to,SizeType to_offset,SizeType to_dim, const RealArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) RealToSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<from_newdim;i++) RealToSub(to,to_offset*to_newdim+(start+stride*i-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; RealToSub(to,to_offset*to.dims[to_dim]+(i-1),to_dim+1, from,from_offset,from_dim,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) RealToSub(to,to_offset*to_newdim+(v.data[i]-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; Real *to_p=to.data+to_offset; Real *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Use as: RealGetSub(a,Colon,Index,3,Range,3,4,EndMark)=a[:,3,3:4] */ DYMOLA_STATIC RealArray RealGetSub(const RealArray a,...) { RealArray temp; va_list ap; SizeType ndims=a.ndims,trailingsize=1,nargs=0; /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,a); for(;!over;) { enum Subtag tag=va_arg(ap,int); switch (tag) { case Colon:nargs++;break; case RangeRange:va_arg(ap,Integer); /* Fallthru*/ case Range:va_arg(ap,Integer),va_arg(ap,Integer);nargs++;break; case Vector:va_arg(ap,RealArray);nargs++;break; case Index:va_arg(ap,Integer);Assert(ndims>0,"Internal error in subscriptring of array");ndims--;nargs++;break; case EndMark:over=1;break; } } va_end(ap); Assert(nargs<=a.ndims,"Too many subscripts for array"); } temp.ndims=ndims; temp.dims=SizeTemp(ndims); /* Pass 2. Determine size of output */ { Integer over=0; SizeType temp_dim=0,a_dim=0; va_start(ap,a); for(;!over;) { enum Subtag tag=va_arg(ap,int); switch (tag) { case Colon:temp.dims[temp_dim]=a.dims[a_dim];temp_dim++;break; case RangeRange:case Range: { Integer start,stop,stride=1,num; start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=1+(stop-start)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=a.dims[a_dim]),"Range subscripting: start out of range"); Assert((stop >=1)&&(stop <=a.dims[a_dim]),"Range subscripting: end out of range"); } temp.dims[temp_dim]=num; temp_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(v.ndims==1,"Array subscripting: only vectors (and scalars) allowed as indicies"); temp.dims[temp_dim]=v.dims[0]; for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=a.dims[a_dim]),"Array subscripting: vector index out of range"); } temp_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert((i>=1)&&(i<=a.dims[a_dim]),"Array subscripting: scalar index out of range"); break; } case EndMark:over=1;break; } a_dim++; } va_end(ap); { SizeType i; for(i=nargs;i<a.ndims;i++) { temp.dims[temp_dim++]=a.dims[i]; trailingsize*=a.dims[i]; } } } temp.data=RealTemp(CommonNrElements(temp.ndims, temp.dims)); /* Pass 3. Copy output */ { struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,a); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); RealFromSub(temp,0,0,a,0,0,trailingsize,apt); } return temp; } /* Use as RealPutSub(a, out,Index,3,Colon,Range,3,4) yields out[3,:,3:4]=a; */ DYMOLA_STATIC RealArray RealCopy(const RealArray a) { int i,imax; RealArray temp; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;++i) temp.dims[i]=a.dims[i]; imax=RealNrElements(a); temp.data=RealTemp(imax); for(i=0;i<imax;++i) temp.data[i]=a.data[i]; return temp; } DYMOLA_STATIC void RealPutSub(const RealArray ain,RealArray out,...) { RealArray a; va_list ap; SizeType out_dim=0,a_dim=0,trailingsize=1,nargs=0; a=RealCopy(ain); /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,out); for(;!over;) { enum Subtag tag=va_arg(ap,int); switch (tag) { case Colon: Assert(out_dim<out.ndims,"Internal error in subscripting (:)"); Assert(a_dim<a.ndims,"Internal error in subscripting (:)"); Assert(out.dims[out_dim]==a.dims[a_dim],"Assignment array subscripting: A[:]=B must have identical sizes"); out_dim++; a_dim++; break; case RangeRange:case Range: { Integer start,stop,stride=1,num; Assert(out_dim<out.ndims,"Internal error in subscripting: range"); Assert(a_dim<a.ndims,"Internal error in subscripting: range "); start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=(stop-start+stride)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=out.dims[out_dim]),"Assignment array subscripting: start of range out of bounds"); Assert((stop>=1)&&(stop<=out.dims[out_dim]),"Assignment array subscripting: end of range out of bounds"); } Assert(a.dims[a_dim]==num,"Assignment array subscripting: A[a:b]=B must have identical sizes"); out_dim++; a_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(out_dim<out.ndims,"Internal error in vector subscripting"); Assert(a_dim<a.ndims,"Internal error in vector subscripting"); Assert(v.ndims==1,"Assignment array subscripting: array index must be a vector"); Assert(a.dims[a_dim]==v.dims[0],"Assignment array subscripting: A[vect]=B must have identical sizes"); for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=out.dims[out_dim]),"Assignment array subscripting: vector index out of bounds"); } out_dim++; a_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert(out_dim<out.ndims,"Internal error in scalar subscripting"); Assert((i>=1)&&(i<=out.dims[out_dim]),"Assignment array subscripting: scalar index out of bounds"); out_dim++; break; } case EndMark:over=1;break; } } va_end(ap); Assert(a.ndims-a_dim==out.ndims-out_dim,"Assignment array subscripting: unequal number of dimensions"); { SizeType i; for(i=a_dim;i<a.ndims;i++) { trailingsize*=a.dims[i]; Assert(a.dims[i]==out.dims[(i-a_dim)+out_dim],"Internal error in subscripting"); } } } /* Pass 2. Copy output */ { struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,out); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); RealToSub(out,0,0,a,0,0,trailingsize,apt); } } /* For each operation Op(...) we create a temporary result res */ /* and call OpAssign(res,...) */ /* The operations Op(...) are convenient and used in the code */ /* Fill */ DYMOLA_STATIC RealArray RealFillAssign(RealArray res,const Real t) { SizeType i,prodsize; prodsize=RealNrElements(res); for(i=0;i<prodsize;i++) res.data[i]=t; return res; } DYMOLA_STATIC RealArray RealFill(const Real t,SizeType ndims,...) { va_list ap; RealArray temp; va_start(ap,ndims); temp=RealFillAssign(RealVaTemporary(ndims,ap),t); va_end(ap); return temp; } DYMOLA_STATIC RealArray RealFillArray(const RealArray a,SizeType ndims,...) { va_list ap; int i,j,inputProd,fillProd; RealArray temp; temp.ndims=a.ndims+ndims; temp.dims=SizeTemp(temp.ndims); va_start(ap,ndims); for(i=0;i<ndims;++i) temp.dims[i]=va_arg(ap,SizeType); va_end(ap); for(i=0;i<a.ndims;++i) temp.dims[i+ndims]=a.dims[i]; fillProd=1; for(i=0;i<ndims;++i) fillProd*=temp.dims[i]; inputProd=RealNrElements(a); temp.data=RealTemp(inputProd*fillProd); for(i=0;i<inputProd;++i) { for(j=0;j<fillProd;j++) { temp.data[i+j*inputProd]=a.data[i]; } } return temp; } DYMOLA_STATIC Real Realscalar(const RealArray a) { Assert(RealNrElements(a)==1,"scalar requires exactly one element"); return a.data[0]; } /* Matrix operations not limited to numeric matrices */ DYMOLA_STATIC RealArray Realvector(const RealArray a) { RealArray res; #ifndef NDEBUG Integer i,found_non_one=0; for(i=0;i<a.ndims;i++) {if (a.dims[i]>1) {Assert(!found_non_one,"vector requires exactly one vector non-unit dimension");found_non_one=1;}} #endif res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=RealNrElements(a); res.data=a.data; return res; } DYMOLA_STATIC RealArray Realmatrix(const RealArray a) { RealArray res; res.ndims=2; res.dims=SizeTemp(2); res.dims[0]=a.dims[0]; res.dims[1]=(a.ndims<2)?1:a.dims[1]; res.data=a.data; Assert(RealNrElements(a)==RealNrElements(res),"matrix requires size(x,i)=1 for i>2"); return res; } DYMOLA_STATIC RealArray Realtranspose(const RealArray a) { RealArray res; Integer i,j,k,remsize; res.ndims=a.ndims; Assert(a.ndims>=2,"transpose requires ndims>=2"); res.dims=SizeTemp(a.ndims); res.dims[0]=a.dims[1]; res.dims[1]=a.dims[0]; remsize=1; for(i=2;i<a.ndims;i++) { remsize*=(res.dims[i]=a.dims[i]); } res.data=RealTemp(CommonNrElements(res.ndims, res.dims)); for(i=0;i<res.dims[0];i++) for(j=0;j<res.dims[1];j++) { for(k=0;k<remsize;k++) { res.data[(i*res.dims[1]+j)*remsize+k]=a.data[(j*a.dims[1]+i)*remsize+k]; } } return res; } DYMOLA_STATIC RealArray Realouterproduct(const RealArray a,const RealArray b) { Assert(a.ndims==1,"Outerproduct require a vector as first argument"); Assert(b.ndims==1,"Outerproduct require a vector as second argument"); { SizeType na=a.dims[0],nb=b.dims[0]; SizeType i,j; RealArray res=RealTemporaryMatrix(na,nb); for(i=0;i<na;i++) { Real ai=a.data[i]; for(j=0;j<nb;j++) res.data[i*nb+j]=ai*b.data[j]; } return res; } } DYMOLA_STATIC RealArray Realsymmetric(const RealArray a) { RealArray res; Integer i,j,n=a.dims[0]; Assert(a.ndims==2,"symmetric requires ndims==2"); Assert(a.dims[0]==a.dims[1],"symmetric requires square matrix"); res=RealTemporaryMatrix(n,n); for(i=0;i<n;i++) { for(j=0;j<=i;j++) res.data[i*n+j]=a.data[j*n+i]; for(;j<n;j++) res.data[i*n+j]=a.data[i*n+j]; } return res; } /* End of common routines for String*/ /* Basic operations, add, subtract, scale*/ /* For each operation Op(...) we create a temporary result res */ /* and call OpAssign(res,...) */ /* The operations Op(...) are convenient and used in the code */ DYMOLA_STATIC RealArray RealAddAssign(RealArray res,const RealArray a,const RealArray b) { SizeType prodsize,i; Assert(RealMatchingSizes(a,b),"Add of arrays require arguments of matching size"); Assert(RealMatchingSizes(res,a),"Add of arrays require result of matching size"); prodsize=RealNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i]+b.data[i]; return res; } DYMOLA_STATIC RealArray RealAdd(const RealArray a,const RealArray b) { return RealAddAssign(RealMatch(a),a,b); } DYMOLA_STATIC RealArray RealSubtractAssign(RealArray res,const RealArray a,const RealArray b) { SizeType prodsize,i; Assert(RealMatchingSizes(a,b),"Subtract of arrays require arguments of matching size"); Assert(RealMatchingSizes(res,a),"Subtract of arrays require result of matching size"); prodsize=RealNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i]-b.data[i]; return res; } DYMOLA_STATIC RealArray RealSubtract(const RealArray a,const RealArray b) { return RealSubtractAssign(RealMatch(a),a,b); } DYMOLA_STATIC RealArray RealScaleAssign(RealArray res,const RealArray a,const Real t) { SizeType i,prodsize; Assert(RealMatchingSizes(res,a),"Array times scalar require result of matching size"); prodsize=RealNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=t*a.data[i]; return res; } DYMOLA_STATIC RealArray RealScale(const RealArray a,const Real t) { return RealScaleAssign(RealMatch(a),a,t); } DYMOLA_STATIC RealArray RealMinusAssign(RealArray res,const RealArray a) { SizeType i,prodsize; Assert(RealMatchingSizes(res,a),"Negating a matrix require result of matching size"); prodsize=RealNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=-a.data[i]; return res; } DYMOLA_STATIC RealArray RealMinus(const RealArray a) { return RealMinusAssign(RealMatch(a),a); } /* sum, max, min, and product */ DYMOLA_STATIC Real Realsum(const RealArray a) { Real res=0; Integer max_elem=RealNrElements(a); Integer i; for(i=0;i<max_elem;i++) res+=a.data[i]; return res; } DYMOLA_STATIC Real RealAbssum(const RealArray a) { Real res=0; Integer max_elem=RealNrElements(a); Integer i; for(i=0;i<max_elem;i++) { Real x=a.data[i]; if (x>0) res+=x; else res-=x; } return res; } DYMOLA_STATIC Real RealAbssumDiff(const RealArray a,const RealArray b) { Real res=0; Integer max_elem=RealNrElements(a); Integer i; Assert(max_elem==RealNrElements(b),"Diff"); for(i=0;i<max_elem;i++) { Real xa=a.data[i]; Real xb=b.data[i]; Real scale=1+((xa>0)?xa:-xa); Real x=(xa-xb)/scale; if (x>0) res+=x; else res-=x; } return res; } DYMOLA_STATIC Real Realmax(const RealArray a) { Real res=-DBL_MAX; Integer max_elem=RealNrElements(a); Integer i; for(i=0;i<max_elem;i++) if (a.data[i]>res) res=a.data[i]; return res; } DYMOLA_STATIC Real Realmin(const RealArray a) { Real res=DBL_MAX; Integer max_elem=RealNrElements(a); Integer i; for(i=0;i<max_elem;i++) if (a.data[i]<res) res=a.data[i]; return res; } DYMOLA_STATIC Real Realproduct(const RealArray a) { Real res=1; Integer max_elem=RealNrElements(a); Integer i; for(i=0;i<max_elem;i++) res*=a.data[i]; return res; } DYMOLA_STATIC RealArray Realdiagonal(const RealArray a) { RealArray res; Integer i,j,n; Assert(a.ndims==1,"diagonal requires vector input"); n=a.dims[0]; res=RealTemporaryMatrix(n,n); for(i=0;i<n;i++) for(j=0;j<n;j++) res.data[i*n+j]=(i==j)?a.data[i]:0; return res; } DYMOLA_STATIC RealArray Realcross(const RealArray x,const RealArray y) { RealArray res=RealTemporaryVector(3); Assert((x.ndims==1)&&(y.ndims==1),"cross requires vector input"); Assert(x.dims[0]==3,"cross requires 3-vector input for first argument"); Assert(y.dims[0]==3,"cross requires 3-vector input for second argument"); res.data[0]=x.data[1]*y.data[2]-x.data[2]*y.data[1]; res.data[1]=x.data[2]*y.data[0]-x.data[0]*y.data[2]; res.data[2]=x.data[0]*y.data[1]-x.data[1]*y.data[0]; return res; } DYMOLA_STATIC RealArray Realskew(const RealArray x) { RealArray res=RealTemporaryMatrix(3,3); Assert(x.ndims==1,"skew requires vector input"); Assert(x.dims[0]==3,"skew requires 3-vector input"); SetRealElement(0,res,1,1); SetRealElement(-RealElement(x,3),res,1,2); SetRealElement(RealElement(x,2),res,1,3); SetRealElement(RealElement(x,3),res,2,1); SetRealElement(0,res,2,2); SetRealElement(-RealElement(x,1),res,2,3); SetRealElement(-RealElement(x,2),res,3,1); SetRealElement(RealElement(x,1),res,3,2); SetRealElement(0,res,3,3); return res; } /* Multiply */ DYMOLA_STATIC RealArray RealMultiplyMMAssign(RealArray res, const RealArray a,const RealArray b) { SizeType i,j,k,imax,jmax,kmax; Assert(res.ndims==2,"Matrix multiply gives a matrix as result"); Assert(a.ndims==2,"Matrix multiply requires that first operand is a matrix"); Assert(b.ndims==2,"Matrix multiply requires that second operand is a matrix"); Assert(res.dims[0]==a.dims[0],"Matrix multiply requires that first dimension of result and first argument match"); Assert(res.dims[1]==b.dims[1],"Matrix multiply requires that second dimension of result and second argument match"); Assert(a.dims[1]==b.dims[0],"Matrix multiply requires that inner dimensions of operands match"); imax=res.dims[0]; jmax=res.dims[1]; kmax=a.dims[1]; for(i=0;i<imax;i++) for(j=0;j<jmax;j++) { Real d=0; for(k=0;k<kmax;k++) d+=a.data[i*kmax+k]*b.data[k*jmax+j]; res.data[i*jmax+j]=d; } return res; } DYMOLA_STATIC RealArray RealMultiplyMVAssign(RealArray res,const RealArray a,const RealArray b) { SizeType i,j,imax,jmax; Assert(a.ndims==2,"Matrix times vector requires a matrix as first operand"); Assert(b.ndims==1,"Matrix times vector requires a vector as second operand"); Assert(res.ndims==1,"Matrix times vector gives a vector result"); Assert(res.dims[0]==a.dims[0],"Matrix times vector: requires size(M*v,1)=size(M,1)"); Assert(a.dims[1]==b.dims[0],"Matrix times vector: requires size(M,2)==size(v,1)"); imax=a.dims[0]; jmax=a.dims[1]; for(i=0;i<imax;i++) { Real d=0; for(j=0;j<jmax;j++) d+=a.data[i*jmax+j]*b.data[j]; res.data[i]=d; } return res; } DYMOLA_STATIC RealArray RealMultiplyVMAssign(RealArray res,const RealArray a,const RealArray b) { SizeType i,j,imax,jmax; Assert(a.ndims==1,"Vector times matrix requires a vector as first operand"); Assert(b.ndims==2,"Vector times matrix requires a matrix as second operand"); Assert(res.ndims==1,"Vector times matrix gives a vector result"); Assert(res.dims[0]==b.dims[1],"Vector times matrix: requires size(v*M,1)=size(M,2)"); Assert(a.dims[0]==b.dims[0],"Vector times matrix: requires size(v,1)=size(M,1)"); imax=b.dims[1]; jmax=b.dims[0]; for(i=0;i<imax;i++) { Real d=0; for(j=0;j<jmax;j++) d+=a.data[j]*b.data[j*imax+i]; res.data[i]=d; } return res; } DYMOLA_STATIC Real RealMultiplyVV(const RealArray a,const RealArray b) { SizeType i,imax; Real d=0; Assert(a.ndims==1,"Scalar product requires vector as first operand"); Assert(b.ndims==1,"Scalar product requires vector as second operand"); Assert(a.dims[0]==b.dims[0],"Scalar product requires vectors of matching size"); imax=a.dims[0]; for(i=0;i<imax;i++) d+=a.data[i]*b.data[i]; return d; } DYMOLA_STATIC RealArray RealMultiplyMM(const RealArray a,const RealArray b) { return RealMultiplyMMAssign(RealTemporaryMatrix(a.dims[0],b.dims[1]),a,b); } DYMOLA_STATIC RealArray RealMultiplyMV(const RealArray a,const RealArray b) { return RealMultiplyMVAssign(RealTemporaryVector(a.dims[0]),a,b); } DYMOLA_STATIC RealArray RealMultiplyVM(const RealArray a,const RealArray b) { return RealMultiplyVMAssign(RealTemporaryVector(b.dims[1]),a,b); } DYMOLA_STATIC RealArray RealIdentity(SizeType n) { RealArray res; Integer i,j; res.ndims=2; res.dims=SizeTemp(2); res.dims[0]=res.dims[1]=n; res.data=RealTemp(n*n); for(i=0;i<n;i++) for(j=0;j<n;j++) res.data[i*n+j]=(i==j); return res; } DYMOLA_STATIC RealArray RealPow(const RealArray a,const Integer n) { Assert(n>=0,"Matrices can only be raised to positive integer"); Assert(a.ndims==2,"Matrix raised to a positive integer requires a matrix as first operand"); Assert(a.dims[0]==a.dims[1],"Matrix raised to a positive integer requires a square matrix as first operand"); if (n==1) return a; else if (n==0) return RealIdentity(a.dims[0]); else { if (n%2) { return RealMultiplyMM(RealPow(a,n-1),a); } else { RealArray ahalf=RealPow(a,n/2); return RealMultiplyMM(ahalf,ahalf); } } } /* For from:stride:to */ DYMOLA_STATIC RealArray RealRange(const Real from,const Real to,const Real stride) { Real extraStride=stride; Real diff=to-from; Real extra=0; Integer num; Assert(stride!=0,"range requires non-zero stride"); if (stride<0) { diff=-diff; extraStride=-extraStride; } if (extraStride!=floor(extraStride)) { extra+=fabs(diff); } if (diff!=floor(diff)) { extra+=fabs(from)+fabs(to); } num=1+(Integer)floor((diff+extra*1.11022302462516E-016)/extraStride); if (num<0) num=0; { RealArray res=RealTemporaryVector(num); Integer i; for(i=0;i<num;i++) SetRealElement(from+i*stride,res,i+1); return res; } } /* End of common routines with Integer */ /* Unique routines */ DYMOLA_STATIC RealArray linspace(const Real from,const Real to,const Integer n) { RealArray res=RealTemporaryVector(n); Integer i; Real delta=(to-from)/(n-1); Assert(n>=2,"Linspace number of point>=2"); for(i=0;i<n-1;i++) res.data[i]=from+delta*i; res.data[n-1]=to; /* Guard against roundoff errors.*/ return res; } /* Go from IntegerArray to RealArray */ DYMOLA_STATIC RealArray RealConvertInteger(const IntegerArray a) { RealArray res; SizeType i,n; res.ndims=a.ndims; res.dims=a.dims; n=CommonNrElements(res.ndims, res.dims); res.data=RealTemp(n); for(i=0;i<n;i++) res.data[i]=a.data[i]; return res; } DYMOLA_STATIC IntegerArray IntegerConvertReal(const RealArray a) { IntegerArray res; SizeType i,n; res.ndims=a.ndims; res.dims=a.dims; n=CommonNrElements(res.ndims, res.dims); res.data=IntegerTemp(n); for(i=0;i<n;i++) res.data[i]=real2integer(a.data[i]); return res; } /* Routines for moutil.h */ #if 0 && !defined(LINALG_PACK) #error #endif DYMOLA_STATIC RealArray RealInverse(const RealArray A) { Assert(A.ndims==2,"Can only invert matrices"); Assert(A.dims[0]==A.dims[1],"Can only invert square matrices"); { RealArray Ainv=RealMatch(A); MarkObject returnMark=PushMark(); Real*RWork=RealTemp(A.dims[0]*A.dims[0]+4+6*A.dims[0]); Integer*IWork=IntegerTemp(A.dims[0]*2+1); SizeType i1,i2,i3,i4,i,j,Ev=0; SizeType Factored=0,IError=0; i1 = A.dims[0]; i2 = A.dims[1]; i3 = 0; i4 = 3; for(i=0;i<A.dims[0];++i) { double T=0; double*b=Ainv.data+i*A.dims[0]; for(j=0;j<A.dims[0];++j) b[j]=0; b[i]=1; dymli2_(&i3,&i4,A.data,&i1,&i2,b, &T,&Ev,&Ev,RWork,IWork,&Factored,&IError); if (IError!=0 && A.dims[0]==1) { Ainv.data[0]=0; IError=0; } Assert(IError==0,"Inverse failed"); } PopMark(returnMark); return Ainv; } } DYMOLA_STATIC RealArray RealScaleDiv(const RealArray a,const Real t) { Assert(t!=0,"Division by zero in function RealScaleDiv"); return RealScaleAssign(RealMatch(a),a,1/t); } /* Routines for Integer */ /* Test for size compatibility, used in assertions */ DYMOLA_STATIC Integer IntegerMatchingSizes(const IntegerArray a,const IntegerArray b) { SizeType i; if (a.ndims!=b.ndims) return 0; for(i=0;i<a.ndims;i++) {if(a.dims[i]!=b.dims[i]) return 0;} return 1; } /* Return total number of elements */ DYMOLA_STATIC SizeType IntegerNrElements(const IntegerArray a) { SizeType prodsize=1; SizeType i; for(i=0;i<a.ndims;i++) prodsize*=a.dims[i]; return prodsize; } /* Create Array-temporaries given the dimensions */ /* Internal: Use an existing va_list */ DYMOLA_STATIC IntegerArray IntegerVaTemporarySize(SizeType ndims,va_list ap) { IntegerArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC IntegerArray IntegerVaTemporary(SizeType ndims,va_list ap) { IntegerArray temp=IntegerVaTemporarySize(ndims,ap); temp.data=IntegerTemp(IntegerNrElements(temp)); return temp; } /* Construct a temporary of the same size as a */ DYMOLA_STATIC IntegerArray IntegerMatch(const IntegerArray a) { IntegerArray temp; SizeType i; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;i++) temp.dims[i]=a.dims[i]; temp.data=IntegerTemp(IntegerNrElements(a)); return temp; } /* Construct array from sizes, using variable number of arguments */ DYMOLA_STATIC IntegerArray IntegerTemporary(SizeType ndims,...) { IntegerArray temp; va_list ap; va_start(ap,ndims); temp=IntegerVaTemporary(ndims,ap); va_end(ap); return temp; } /* Special cases for vectors and matrices (most often used) */ DYMOLA_STATIC IntegerArray IntegerTemporaryMatrix(SizeType r,SizeType c) { IntegerArray temp; temp.ndims=2; temp.dims=SizeTemp(2); temp.dims[0]=r;temp.dims[1]=c; temp.data=IntegerTemp(r*c); return temp; } DYMOLA_STATIC IntegerArray IntegerTemporaryVector(SizeType r) { IntegerArray temp; temp.ndims=1; temp.dims=SizeTemp(1); temp.dims[0]=r; temp.data=IntegerTemp(r); return temp; } /* Assignment */ DYMOLA_STATIC void IntegerAssign(IntegerArray a,const IntegerArray b) { SizeType prodsize=IntegerNrElements(a); SizeType i; Assert(IntegerMatchingSizes(a,b),"Array dimensions did not match"); for(i=0;i<prodsize;i++) a.data[i]=b.data[i]; } /* Indexing to set/get elements */ DYMOLA_STATIC Integer IntegerElement(const IntegerArray a,...) { SizeType index; va_list ap; va_start(ap,a); index=FindIndex(a.ndims,a.dims,ap); va_end(ap); return a.data[index]; } /* Sizes */ DYMOLA_STATIC Integer IntegerSize(const IntegerArray a,SizeType i) { Assert((i>=1)&&(i<=a.ndims),"Size must be between 1 and ndims of array"); return a.dims[i-1]; } DYMOLA_STATIC IntegerArray IntegerSizes(const IntegerArray a) { IntegerArray res; Integer i; res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=a.ndims; res.data=IntegerTemp(a.ndims); for(i=0;i<a.ndims;i++) res.data[i]=a.dims[i]; return res; } /* Set element, note that val is prior to the index list. */ DYMOLA_STATIC void SetIntegerElement(Integer val,IntegerArray a,...) { SizeType index; va_list ap; va_start(ap,a); index=FindIndex(a.ndims,a.dims,ap); a.data[index]=val; va_end(ap); } /* For debug write out */ DYMOLA_STATIC void IntegerWrite(const IntegerArray a) { SizeType i; DymosimMessageInt("Dims: ",a.ndims); for(i=0;i<a.ndims;i++) DymosimMessageInt(" ",a.dims[i]); for(i=0;i<IntegerNrElements(a);i++) DymosimMessageMatrixElement("",i,1,a.data[i]); } /* Construct Arrays from other arrays */ DYMOLA_STATIC IntegerArray IntegerArrayArray(SizeType narg,IntegerArray first,...) { IntegerArray res; SizeType i,j,prodsize; va_list ap; res.ndims=first.ndims+1; res.dims=SizeTemp(res.ndims); res.dims[0]=narg; for(i=1;i<res.ndims;i++) res.dims[i]=first.dims[i-1]; prodsize=IntegerNrElements(first); res.data=IntegerTemp(prodsize*narg); va_start(ap,first); for(i=0;i<narg;i++) { IntegerArray next; next=(i!=0)?va_arg(ap,IntegerArray):first; Assert(IntegerMatchingSizes(first,next),"Arrays in array must be of equal sizes"); for(j=0;j<prodsize;j++) res.data[i*prodsize+j]=next.data[j]; } va_end(ap); return res; } /* Construct arrays from scalars */ DYMOLA_STATIC IntegerArray IntegerScalarArray(SizeType narg,...) { IntegerArray res; SizeType i; va_list ap; res=IntegerTemporaryVector(narg); va_start(ap,narg); for(i=0;i<narg;i++) { res.data[i]=va_arg(ap,Integer); } va_end(ap); return res; } /* Get/Put of submatrices, i.e. a[i,:,v,1:4] */ /* Actual get of a submatrix */ DYMOLA_STATIC void IntegerFromSub(IntegerArray to,SizeType to_offset,SizeType to_dim, const IntegerArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) IntegerFromSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<to_newdim;i++) IntegerFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+(start+stride*i-1),from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; IntegerFromSub(to,to_offset,to_dim, from,from_offset*from.dims[from_dim]+i-1,from_dim+1,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) IntegerFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+v.data[i]-1,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; Integer *to_p=to.data+to_offset; Integer *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Concatenate along dimensions 'along' (1..ndims) and given nargs arguments */ DYMOLA_STATIC IntegerArray IntegerCat(SizeType along,SizeType nargs,IntegerArray first,...) { IntegerArray res; va_list ap; SizeType i,j; res.ndims=first.ndims; res.dims=SizeTemp(res.ndims); along--; /* Adapt to C usage */ { /* Pass 1: determine size of output */ for(j=0;j<first.ndims;j++) res.dims[j]=first.dims[j]; /* Starting values */ va_start(ap,first); for(i=1;i<nargs;i++) { IntegerArray a; a=va_arg(ap,IntegerArray); Assert(a.ndims==first.ndims,"Number of dimensions must match for cat"); for(j=0;j<a.ndims;j++) if (j!=along) {Assert(first.dims[j]==a.dims[j],"Sizes must match for cat");} res.dims[along]+=a.dims[along]; } va_end(ap); } res.data=IntegerTemp(CommonNrElements(res.ndims, res.dims)); { /* Pass 2: copy data */ SizeType presize=1; /* Blocks */ SizeType trailingsize=1; /* Elements in each block */ SizeType marker=0; /* How far are in res along dimension along */ for(i=0;i<along;i++) presize*=res.dims[i]; for(i=along+1;i<res.ndims;i++) trailingsize*=res.dims[i]; va_start(ap,first); for(i=0;i<nargs;i++) { SizeType pre,current,trailing; IntegerArray a; if (i!=0) a=va_arg(ap,IntegerArray); else a=first; for(pre=0;pre<presize;pre++) for(current=0;current<a.dims[along];current++) for(trailing=0;trailing<trailingsize;trailing++) res.data[(pre*res.dims[along]+(current+marker))*trailingsize+trailing]= a.data[(pre*a.dims[along]+current)*trailingsize+trailing]; marker+=a.dims[along]; } va_end(ap); } return res; } /* The helper in Modelica */ DYMOLA_STATIC IntegerArray IntegerPromote(const IntegerArray a,SizeType n) { IntegerArray res; SizeType i; Assert(n>=a.ndims,"Promote cannot decrease number of dimensions"); res.ndims=n; res.data=a.data; /* No need to copy */ res.dims=SizeTemp(n); for(i=0;i<a.ndims;i++) res.dims[i]=a.dims[i]; for(i=a.ndims;i<n;i++) res.dims[i]=1; return res; } DYMOLA_STATIC IntegerArray IntegerPromoteScalar(const Integer x,SizeType n) { IntegerArray res; Integer i; res.ndims=n; res.data=IntegerTemp(1); res.data[0]=x; res.dims=SizeTemp(n); for(i=0;i<n;i++) res.dims[i]=1; return res; } /* Actual put of submatrix */ DYMOLA_STATIC void IntegerToSub(IntegerArray to,SizeType to_offset,SizeType to_dim, const IntegerArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) IntegerToSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<from_newdim;i++) IntegerToSub(to,to_offset*to_newdim+(start+stride*i-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; IntegerToSub(to,to_offset*to.dims[to_dim]+(i-1),to_dim+1, from,from_offset,from_dim,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) IntegerToSub(to,to_offset*to_newdim+(v.data[i]-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; Integer *to_p=to.data+to_offset; Integer *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Use as: IntegerGetSub(a,Colon,Index,3,Range,3,4,EndMark)=a[:,3,3:4] */ DYMOLA_STATIC IntegerArray IntegerGetSub(const IntegerArray a,...) { IntegerArray temp; va_list ap; SizeType ndims=a.ndims,trailingsize=1,nargs=0; /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,a); for(;!over;) { Integer tag=va_arg(ap,Integer); switch (tag) { case Colon:nargs++;break; case RangeRange:va_arg(ap,Integer); /* Fallthru*/ case Range:va_arg(ap,Integer),va_arg(ap,Integer);nargs++;break; case Vector:va_arg(ap,IntegerArray);nargs++;break; case Index:va_arg(ap,Integer);Assert(ndims>0,"Internal error in subscriptring of array");ndims--;nargs++;break; case EndMark:over=1;break; } } va_end(ap); Assert(nargs<=a.ndims,"Too many subscripts for array"); } temp.ndims=ndims; temp.dims=SizeTemp(ndims); /* Pass 2. Determine size of output */ { Integer over=0; SizeType temp_dim=0,a_dim=0; va_start(ap,a); for(;!over;) { Integer tag=va_arg(ap,Integer); switch (tag) { case Colon:temp.dims[temp_dim]=a.dims[a_dim];temp_dim++;break; case RangeRange:case Range: { Integer start,stop,stride=1,num; start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=1+(stop-start)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=a.dims[a_dim]),"Range subscripting: start out of range"); Assert((stop >=1)&&(stop <=a.dims[a_dim]),"Range subscripting: end out of range"); } temp.dims[temp_dim]=num; temp_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(v.ndims==1,"Array subscripting: only vectors (and scalars) allowed as indicies"); temp.dims[temp_dim]=v.dims[0]; for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=a.dims[a_dim]),"Array subscripting: vector index out of range"); } temp_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert((i>=1)&&(i<=a.dims[a_dim]),"Array subscripting: scalar index out of range"); break; } case EndMark:over=1;break; } a_dim++; } va_end(ap); { SizeType i; for(i=nargs;i<a.ndims;i++) { temp.dims[temp_dim++]=a.dims[i]; trailingsize*=a.dims[i]; } } } temp.data=IntegerTemp(CommonNrElements(temp.ndims, temp.dims)); /* Pass 3. Copy output */ { struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,a); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); IntegerFromSub(temp,0,0,a,0,0,trailingsize,apt); } return temp; } /* Use as IntegerPutSub(a, out,Index,3,Colon,Range,3,4) yields out[3,:,3:4]=a; */ DYMOLA_STATIC IntegerArray IntegerCopy(const IntegerArray a) { int i,imax; IntegerArray temp; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;++i) temp.dims[i]=a.dims[i]; imax=IntegerNrElements(a); temp.data=IntegerTemp(imax); for(i=0;i<imax;++i) temp.data[i]=a.data[i]; return temp; } DYMOLA_STATIC void IntegerPutSub(const IntegerArray ain,IntegerArray out,...) { IntegerArray a; va_list ap; SizeType out_dim=0,a_dim=0,trailingsize=1,nargs=0; a=IntegerCopy(ain); /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,out); for(;!over;) { Integer tag=va_arg(ap,Integer); switch (tag) { case Colon: Assert(out_dim<out.ndims,"Internal error in subscripting (:)"); Assert(a_dim<a.ndims,"Internal error in subscripting (:)"); Assert(out.dims[out_dim]==a.dims[a_dim],"Assignment array subscripting: A[:]=B must have identical sizes"); out_dim++; a_dim++; break; case RangeRange:case Range: { Integer start,stop,stride=1,num; Assert(out_dim<out.ndims,"Internal error in subscripting: range"); Assert(a_dim<a.ndims,"Internal error in subscripting: range "); start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=(stop-start+stride)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=out.dims[out_dim]),"Assignment array subscripting: start of range out of bounds"); Assert((stop>=1)&&(stop<=out.dims[out_dim]),"Assignment array subscripting: end of range out of bounds"); } Assert(a.dims[a_dim]==num,"Assignment array subscripting: A[a:b]=B must have identical sizes"); out_dim++; a_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(out_dim<out.ndims,"Internal error in vector subscripting"); Assert(a_dim<a.ndims,"Internal error in vector subscripting"); Assert(v.ndims==1,"Assignment array subscripting: array index must be a vector"); Assert(a.dims[a_dim]==v.dims[0],"Assignment array subscripting: A[vect]=B must have identical sizes"); for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=out.dims[out_dim]),"Assignment array subscripting: vector index out of bounds"); } out_dim++; a_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert(out_dim<out.ndims,"Internal error in scalar subscripting"); Assert((i>=1)&&(i<=out.dims[out_dim]),"Assignment array subscripting: scalar index out of bounds"); out_dim++; break; } case EndMark:over=1;break; } } va_end(ap); Assert(a.ndims-a_dim==out.ndims-out_dim,"Assignment array subscripting: unequal number of dimensions"); { SizeType i; for(i=a_dim;i<a.ndims;i++) { trailingsize*=a.dims[i]; Assert(a.dims[i]==out.dims[(i-a_dim)+out_dim],"Internal error in subscripting"); } } } /* Pass 2. Copy output */ { struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,out); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); IntegerToSub(out,0,0,a,0,0,trailingsize,apt); } } /* For each operation Op(...) we create a temporary result res */ /* and call OpAssign(res,...) */ /* The operations Op(...) are convenient and used in the code */ /* Fill */ DYMOLA_STATIC IntegerArray IntegerFillAssign(IntegerArray res,const Integer t) { SizeType i,prodsize; prodsize=IntegerNrElements(res); for(i=0;i<prodsize;i++) res.data[i]=t; return res; } DYMOLA_STATIC IntegerArray IntegerFill(const Integer t,SizeType ndims,...) { va_list ap; IntegerArray temp; va_start(ap,ndims); temp=IntegerFillAssign(IntegerVaTemporary(ndims,ap),t); va_end(ap); return temp; } DYMOLA_STATIC IntegerArray IntegerFillArray(const IntegerArray a,SizeType ndims,...) { va_list ap; int i,j,inputProd,fillProd; IntegerArray temp; temp.ndims=a.ndims+ndims; temp.dims=SizeTemp(temp.ndims); va_start(ap,ndims); for(i=0;i<ndims;++i) temp.dims[i]=va_arg(ap,SizeType); va_end(ap); for(i=0;i<a.ndims;++i) temp.dims[i+ndims]=a.dims[i]; fillProd=1; for(i=0;i<ndims;++i) fillProd*=temp.dims[i]; inputProd=IntegerNrElements(a); temp.data=IntegerTemp(inputProd*fillProd); for(i=0;i<inputProd;++i) { for(j=0;j<fillProd;j++) { temp.data[i+j*inputProd]=a.data[i]; } } return temp; } DYMOLA_STATIC Integer Integerscalar(const IntegerArray a) { Assert(IntegerNrElements(a)==1,"scalar requires exactly one element"); return a.data[0]; } /* Matrix operations not limited to numeric matrices */ DYMOLA_STATIC IntegerArray Integervector(const IntegerArray a) { IntegerArray res; #ifndef NDEBUG Integer i,found_non_one=0; for(i=0;i<a.ndims;i++) {if (a.dims[i]>1) {Assert(!found_non_one,"vector requires exactly one vector non-unit dimension");found_non_one=1;}} #endif res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=IntegerNrElements(a); res.data=a.data; return res; } DYMOLA_STATIC IntegerArray Integermatrix(const IntegerArray a) { IntegerArray res; res.ndims=2; res.dims=SizeTemp(2); res.dims[0]=a.dims[0]; res.dims[1]=(a.ndims<2)?1:a.dims[1]; res.data=a.data; Assert(IntegerNrElements(a)==IntegerNrElements(res),"matrix requires size(x,i)=1 for i>2"); return res; } DYMOLA_STATIC IntegerArray Integertranspose(const IntegerArray a) { IntegerArray res; Integer i,j,k,remsize; res.ndims=a.ndims; Assert(a.ndims>=2,"transpose requires ndims>=2"); res.dims=SizeTemp(a.ndims); res.dims[0]=a.dims[1]; res.dims[1]=a.dims[0]; remsize=1; for(i=2;i<a.ndims;i++) { remsize*=(res.dims[i]=a.dims[i]); } res.data=IntegerTemp(CommonNrElements(res.ndims, res.dims)); for(i=0;i<res.dims[0];i++) for(j=0;j<res.dims[1];j++) { for(k=0;k<remsize;k++) { res.data[(i*res.dims[1]+j)*remsize+k]=a.data[(j*a.dims[1]+i)*remsize+k]; } } return res; } DYMOLA_STATIC IntegerArray Integerouterproduct(const IntegerArray a,const IntegerArray b) { Assert(a.ndims==1,"Outerproduct require a vector as first argument"); Assert(b.ndims==1,"Outerproduct require a vector as second argument"); { SizeType na=a.dims[0],nb=b.dims[0]; SizeType i,j; IntegerArray res=IntegerTemporaryMatrix(na,nb); for(i=0;i<na;i++) { Integer ai=a.data[i]; for(j=0;j<nb;j++) res.data[i*nb+j]=ai*b.data[j]; } return res; } } DYMOLA_STATIC IntegerArray Integersymmetric(const IntegerArray a) { IntegerArray res; Integer i,j,n=a.dims[0]; Assert(a.ndims==2,"symmetric requires ndims==2"); Assert(a.dims[0]==a.dims[1],"symmetric requires square matrix"); res=IntegerTemporaryMatrix(n,n); for(i=0;i<n;i++) { for(j=0;j<=i;j++) res.data[i*n+j]=a.data[j*n+i]; for(;j<n;j++) res.data[i*n+j]=a.data[i*n+j]; } return res; } /* End of common routines for String*/ /* Basic operations, add, subtract, scale*/ /* For each operation Op(...) we create a temporary result res */ /* and call OpAssign(res,...) */ /* The operations Op(...) are convenient and used in the code */ DYMOLA_STATIC IntegerArray IntegerAddAssign(IntegerArray res,const IntegerArray a,const IntegerArray b) { SizeType prodsize,i; Assert(IntegerMatchingSizes(a,b),"Add of arrays require arguments of matching size"); Assert(IntegerMatchingSizes(res,a),"Add of arrays require result of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i]+b.data[i]; return res; } DYMOLA_STATIC IntegerArray IntegerAdd(const IntegerArray a,const IntegerArray b) { return IntegerAddAssign(IntegerMatch(a),a,b); } DYMOLA_STATIC IntegerArray IntegerSubtractAssign(IntegerArray res,const IntegerArray a,const IntegerArray b) { SizeType prodsize,i; Assert(IntegerMatchingSizes(a,b),"Subtract of arrays require arguments of matching size"); Assert(IntegerMatchingSizes(res,a),"Subtract of arrays require result of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i]-b.data[i]; return res; } DYMOLA_STATIC IntegerArray IntegerSubtract(const IntegerArray a,const IntegerArray b) { return IntegerSubtractAssign(IntegerMatch(a),a,b); } DYMOLA_STATIC IntegerArray IntegerScaleAssign(IntegerArray res,const IntegerArray a,const Integer t) { SizeType i,prodsize; Assert(IntegerMatchingSizes(res,a),"Array times scalar require result of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=t*a.data[i]; return res; } DYMOLA_STATIC IntegerArray IntegerScale(const IntegerArray a,const Integer t) { return IntegerScaleAssign(IntegerMatch(a),a,t); } DYMOLA_STATIC IntegerArray IntegerMinusAssign(IntegerArray res,const IntegerArray a) { SizeType i,prodsize; Assert(IntegerMatchingSizes(res,a),"Negating a matrix require result of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=-a.data[i]; return res; } DYMOLA_STATIC IntegerArray IntegerMinus(const IntegerArray a) { return IntegerMinusAssign(IntegerMatch(a),a); } /* sum, max, min, and product */ DYMOLA_STATIC Integer Integersum(const IntegerArray a) { Integer res=0; Integer max_elem=IntegerNrElements(a); Integer i; for(i=0;i<max_elem;i++) res+=a.data[i]; return res; } DYMOLA_STATIC Integer IntegerAbssum(const IntegerArray a) { Integer res=0; Integer max_elem=IntegerNrElements(a); Integer i; for(i=0;i<max_elem;i++) { Integer x=a.data[i]; if (x>0) res+=x; else res-=x; } return res; } DYMOLA_STATIC Integer Integermax(const IntegerArray a) { Integer res=INT_MIN; Integer max_elem=IntegerNrElements(a); Integer i; for(i=0;i<max_elem;i++) if (a.data[i]>res) res=a.data[i]; return res; } DYMOLA_STATIC Integer Integermin(const IntegerArray a) { Integer res=INT_MAX; Integer max_elem=IntegerNrElements(a); Integer i; for(i=0;i<max_elem;i++) if (a.data[i]<res) res=a.data[i]; return res; } DYMOLA_STATIC Integer Integerproduct(const IntegerArray a) { Integer res=1; Integer max_elem=IntegerNrElements(a); Integer i; for(i=0;i<max_elem;i++) res*=a.data[i]; return res; } DYMOLA_STATIC IntegerArray Integerdiagonal(const IntegerArray a) { IntegerArray res; Integer i,j,n; Assert(a.ndims==1,"diagonal requires vector input"); n=a.dims[0]; res=IntegerTemporaryMatrix(n,n); for(i=0;i<n;i++) for(j=0;j<n;j++) res.data[i*n+j]=(i==j)?a.data[i]:0; return res; } DYMOLA_STATIC IntegerArray Integercross(const IntegerArray x,const IntegerArray y) { IntegerArray res=IntegerTemporaryVector(3); Assert((x.ndims==1)&&(y.ndims==1),"cross requires vector input"); Assert(x.dims[0]==3,"cross requires 3-vector input for first argument"); Assert(y.dims[0]==3,"cross requires 3-vector input for second argument"); res.data[0]=x.data[1]*y.data[2]-x.data[2]*y.data[1]; res.data[1]=x.data[2]*y.data[0]-x.data[0]*y.data[2]; res.data[2]=x.data[0]*y.data[1]-x.data[1]*y.data[0]; return res; } DYMOLA_STATIC IntegerArray Integerskew(const IntegerArray x) { IntegerArray res=IntegerTemporaryMatrix(3,3); Assert(x.ndims==1,"skew requires vector input"); Assert(x.dims[0]==3,"skew requires 3-vector input"); SetIntegerElement(0,res,1,1); SetIntegerElement(-IntegerElement(x,3),res,1,2); SetIntegerElement(IntegerElement(x,2),res,1,3); SetIntegerElement(IntegerElement(x,3),res,2,1); SetIntegerElement(0,res,2,2); SetIntegerElement(-IntegerElement(x,1),res,2,3); SetIntegerElement(-IntegerElement(x,2),res,3,1); SetIntegerElement(IntegerElement(x,1),res,3,2); SetIntegerElement(0,res,3,3); return res; } /* Multiply */ DYMOLA_STATIC IntegerArray IntegerMultiplyMMAssign(IntegerArray res, const IntegerArray a,const IntegerArray b) { SizeType i,j,k,imax,jmax,kmax; Assert(res.ndims==2,"Matrix multiply gives a matrix as result"); Assert(a.ndims==2,"Matrix multiply requires that first operand is a matrix"); Assert(b.ndims==2,"Matrix multiply requires that second operand is a matrix"); Assert(res.dims[0]==a.dims[0],"Matrix multiply requires that first dimension of result and first argument match"); Assert(res.dims[1]==b.dims[1],"Matrix multiply requires that second dimension of result and second argument match"); Assert(a.dims[1]==b.dims[0],"Matrix multiply requires that inner dimensions of operands match"); imax=res.dims[0]; jmax=res.dims[1]; kmax=a.dims[1]; for(i=0;i<imax;i++) for(j=0;j<jmax;j++) { Integer d=0; for(k=0;k<kmax;k++) d+=a.data[i*kmax+k]*b.data[k*jmax+j]; res.data[i*jmax+j]=d; } return res; } DYMOLA_STATIC IntegerArray IntegerMultiplyMVAssign(IntegerArray res,const IntegerArray a,const IntegerArray b) { SizeType i,j,imax,jmax; Assert(a.ndims==2,"Matrix times vector requires a matrix as first operand"); Assert(b.ndims==1,"Matrix times vector requires a vector as second operand"); Assert(res.ndims==1,"Matrix times vector gives a vector result"); Assert(res.dims[0]==a.dims[0],"Matrix times vector: requires size(M*v,1)=size(M,1)"); Assert(a.dims[1]==b.dims[0],"Matrix times vector: requires size(M,2)==size(v,1)"); imax=a.dims[0]; jmax=a.dims[1]; for(i=0;i<imax;i++) { Integer d=0; for(j=0;j<jmax;j++) { d+=a.data[i*jmax+j]*b.data[j]; } res.data[i]=d; } return res; } DYMOLA_STATIC IntegerArray IntegerMultiplyVMAssign(IntegerArray res,const IntegerArray a,const IntegerArray b) { SizeType i,j,imax,jmax; Assert(a.ndims==1,"Vector times matrix requires a vector as first operand"); Assert(b.ndims==2,"Vector times matrix requires a matrix as second operand"); Assert(res.ndims==1,"Vector times matrix gives a vector result"); Assert(res.dims[0]==b.dims[1],"Vector times matrix: requires size(v*M,1)=size(M,2)"); Assert(a.dims[0]==b.dims[0],"Vector times matrix: requires size(v,1)=size(M,1)"); imax=b.dims[1]; jmax=b.dims[0]; for(i=0;i<imax;i++) { Integer d=0; for(j=0;j<jmax;j++) { d+=a.data[j]*b.data[j*imax+i]; } res.data[i]=d; } return res; } DYMOLA_STATIC Integer IntegerMultiplyVV(const IntegerArray a,const IntegerArray b) { SizeType i,imax; Integer d=0; Assert(a.ndims==1,"Scalar product requires vector as first operand"); Assert(b.ndims==1,"Scalar product requires vector as second operand"); Assert(a.dims[0]==b.dims[0],"Scalar product requires vectors of matching size"); imax=a.dims[0]; for(i=0;i<imax;i++) d+=a.data[i]*b.data[i]; return d; } DYMOLA_STATIC IntegerArray IntegerMultiplyMM(const IntegerArray a,const IntegerArray b) { return IntegerMultiplyMMAssign(IntegerTemporaryMatrix(a.dims[0],b.dims[1]),a,b); } DYMOLA_STATIC IntegerArray IntegerMultiplyMV(const IntegerArray a,const IntegerArray b) { return IntegerMultiplyMVAssign(IntegerTemporaryVector(a.dims[0]),a,b); } DYMOLA_STATIC IntegerArray IntegerMultiplyVM(const IntegerArray a,const IntegerArray b) { return IntegerMultiplyVMAssign(IntegerTemporaryVector(b.dims[1]),a,b); } DYMOLA_STATIC IntegerArray IntegerIdentity(SizeType n) { IntegerArray res; Integer i,j; res.ndims=2; res.dims=SizeTemp(2); res.dims[0]=res.dims[1]=n; res.data=IntegerTemp(n*n); for(i=0;i<n;i++) for(j=0;j<n;j++) res.data[i*n+j]=(i==j); return res; } DYMOLA_STATIC IntegerArray IntegerPow(const IntegerArray a,const Integer n) { Assert(n>=0,"Matrices can only be raised to positive integer"); Assert(a.ndims==2,"Matrix raised to a positive integer requires a matrix as first operand"); Assert(a.dims[0]==a.dims[1],"Matrix raised to a positive integer requires a square matrix as first operand"); if (n==1) return a; else if (n==0) return IntegerIdentity(a.dims[0]); else { if (n%2) { return IntegerMultiplyMM(IntegerPow(a,n-1),a); } else { IntegerArray ahalf=IntegerPow(a,n/2); return IntegerMultiplyMM(ahalf,ahalf); } } } /* For from:stride:to */ DYMOLA_STATIC IntegerArray IntegerRange(const Integer from,const Integer to,const Integer stride) { Integer num; Assert(stride!=0,"range requires non-zero stride"); num=(Integer)floor((to-from)*1.0/stride)+1; if (num<0) num=0; { IntegerArray res=IntegerTemporaryVector(num); Integer i; for(i=0;i<num;i++) SetIntegerElement(from+i*stride,res,i+1); return res; } } /* Test for size compatibility, used in assertions */ DYMOLA_STATIC Integer StringMatchingSizes(const StringArray a,const StringArray b) { SizeType i; if (a.ndims!=b.ndims) return 0; for(i=0;i<a.ndims;i++) {if(a.dims[i]!=b.dims[i]) return 0;} return 1; } /* Return total number of elements */ DYMOLA_STATIC SizeType StringNrElements(const StringArray a) { SizeType prodsize=1; SizeType i; for(i=0;i<a.ndims;i++) prodsize*=a.dims[i]; return prodsize; } /* Create Array-temporaries given the dimensions */ /* Internal: Use an existing va_list */ DYMOLA_STATIC StringArray StringVaTemporarySize(SizeType ndims,va_list ap) { StringArray temp; SizeType i; temp.ndims=ndims; temp.dims=SizeTemp(ndims); for(i=0;i<ndims;i++) temp.dims[i]=va_arg(ap,SizeType); return temp; } DYMOLA_STATIC StringArray StringVaTemporary(SizeType ndims,va_list ap) { StringArray temp=StringVaTemporarySize(ndims,ap); temp.data=StringTemp(StringNrElements(temp)); return temp; } /* Construct a temporary of the same size as a */ DYMOLA_STATIC StringArray StringMatch(const StringArray a) { StringArray temp; SizeType i; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;i++) temp.dims[i]=a.dims[i]; temp.data=StringTemp(StringNrElements(a)); return temp; } /* Construct array from sizes, using variable number of arguments */ DYMOLA_STATIC StringArray StringTemporary(SizeType ndims,...) { StringArray temp; va_list ap; va_start(ap,ndims); temp=StringVaTemporary(ndims,ap); va_end(ap); return temp; } /* Special cases for vectors and matrices (most often used) */ DYMOLA_STATIC StringArray StringTemporaryMatrix(SizeType r,SizeType c) { StringArray temp; temp.ndims=2; temp.dims=SizeTemp(2); temp.dims[0]=r;temp.dims[1]=c; temp.data=StringTemp(r*c); return temp; } DYMOLA_STATIC StringArray StringTemporaryVector(SizeType r) { StringArray temp; temp.ndims=1; temp.dims=SizeTemp(1); temp.dims[0]=r; temp.data=StringTemp(r); return temp; } /* Assignment */ DYMOLA_STATIC void StringAssign(StringArray a,const StringArray b) { SizeType prodsize=StringNrElements(a); SizeType i; Assert(StringMatchingSizes(a,b),"Array dimensions did not match"); for(i=0;i<prodsize;i++) a.data[i]=b.data[i]; } /* Indexing to set/get elements */ DYMOLA_STATIC const char* StringElement(const StringArray a,...) { SizeType index; va_list ap; va_start(ap,a); index=FindIndex(a.ndims,a.dims,ap); va_end(ap); return a.data[index]; } /* Sizes */ DYMOLA_STATIC Integer StringSize(const StringArray a,SizeType i) { Assert((i>=1)&&(i<=a.ndims),"Size must be between 1 and ndims of array"); return a.dims[i-1]; } DYMOLA_STATIC IntegerArray StringSizes(const StringArray a) { IntegerArray res; Integer i; res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=a.ndims; res.data=IntegerTemp(a.ndims); for(i=0;i<a.ndims;i++) res.data[i]=a.dims[i]; return res; } /* Set element, note that val is prior to the index list. */ DYMOLA_STATIC void SetStringElement(const char* val,StringArray a,...) { SizeType index; va_list ap; va_start(ap,a); index=FindIndex(a.ndims,a.dims,ap); a.data[index]=val; va_end(ap); } /* For debug write out */ DYMOLA_STATIC void StringWrite(const StringArray a) { SizeType i; DymosimMessageInt("Dims: ",a.ndims); for(i=0;i<a.ndims;i++) DymosimMessageInt(" ",a.dims[i]); for(i=0;i<StringNrElements(a);i++) DymosimMessage((char *) a.data[i]); } /* Construct Arrays from other arrays */ DYMOLA_STATIC StringArray StringArrayArray(SizeType narg,StringArray first,...) { StringArray res; SizeType i,j,prodsize; va_list ap; res.ndims=first.ndims+1; res.dims=SizeTemp(res.ndims); res.dims[0]=narg; for(i=1;i<res.ndims;i++) res.dims[i]=first.dims[i-1]; prodsize=StringNrElements(first); res.data=StringTemp(prodsize*narg); va_start(ap,first); for(i=0;i<narg;i++) { StringArray next; next=(i!=0)?va_arg(ap,StringArray):first; Assert(StringMatchingSizes(first,next),"Arrays in array must be of equal sizes"); for(j=0;j<prodsize;j++) res.data[i*prodsize+j]=next.data[j]; } va_end(ap); return res; } /* Construct arrays from scalars */ DYMOLA_STATIC StringArray StringScalarArray(SizeType narg,...) { StringArray res; SizeType i; va_list ap; res=StringTemporaryVector(narg); va_start(ap,narg); for(i=0;i<narg;i++) { res.data[i]=va_arg(ap,const char*); } va_end(ap); return res; } /* Get/Put of submatrices, i.e. a[i,:,v,1:4] */ /* Actual get of a submatrix */ DYMOLA_STATIC void StringFromSub(StringArray to,SizeType to_offset,SizeType to_dim, const StringArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) StringFromSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<to_newdim;i++) StringFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+(start+stride*i-1),from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; StringFromSub(to,to_offset,to_dim, from,from_offset*from.dims[from_dim]+i-1,from_dim+1,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) StringFromSub(to,to_offset*to_newdim+i,to_dim+1, from,from_offset*from_newdim+v.data[i]-1,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; String *to_p=to.data+to_offset; String *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Concatenate along dimensions 'along' (1..ndims) and given nargs arguments */ DYMOLA_STATIC StringArray StringCat(SizeType along,SizeType nargs,StringArray first,...) { StringArray res; va_list ap; SizeType i,j; res.ndims=first.ndims; res.dims=SizeTemp(res.ndims); along--; /* Adapt to C usage */ { /* Pass 1: determine size of output */ for(j=0;j<first.ndims;j++) res.dims[j]=first.dims[j]; /* Starting values */ va_start(ap,first); for(i=1;i<nargs;i++) { StringArray a; a=va_arg(ap,StringArray); Assert(a.ndims==first.ndims,"Number of dimensions must match for cat"); for(j=0;j<a.ndims;j++) if (j!=along) {Assert(first.dims[j]==a.dims[j],"Sizes must match for cat");} res.dims[along]+=a.dims[along]; } va_end(ap); } res.data=StringTemp(CommonNrElements(res.ndims, res.dims)); { /* Pass 2: copy data */ SizeType presize=1; /* Blocks */ SizeType trailingsize=1; /* Elements in each block */ SizeType marker=0; /* How far are in res along dimension along */ for(i=0;i<along;i++) presize*=res.dims[i]; for(i=along+1;i<res.ndims;i++) trailingsize*=res.dims[i]; va_start(ap,first); for(i=0;i<nargs;i++) { SizeType pre,current,trailing; StringArray a; if (i!=0) a=va_arg(ap,StringArray); else a=first; for(pre=0;pre<presize;pre++) for(current=0;current<a.dims[along];current++) for(trailing=0;trailing<trailingsize;trailing++) res.data[(pre*res.dims[along]+(current+marker))*trailingsize+trailing]= a.data[(pre*a.dims[along]+current)*trailingsize+trailing]; marker+=a.dims[along]; } va_end(ap); } return res; } /* The helper in Modelica */ DYMOLA_STATIC StringArray StringPromote(const StringArray a,SizeType n) { StringArray res; SizeType i; Assert(n>=a.ndims,"Promote cannot decrease number of dimensions"); res.ndims=n; res.data=a.data; /* No need to copy */ res.dims=SizeTemp(n); for(i=0;i<a.ndims;i++) res.dims[i]=a.dims[i]; for(i=a.ndims;i<n;i++) res.dims[i]=1; return res; } DYMOLA_STATIC StringArray StringPromoteScalar(const char* x,SizeType n) { StringArray res; Integer i; res.ndims=n; res.data=StringTemp(1); res.data[0]=x; res.dims=SizeTemp(n); for(i=0;i<n;i++) res.dims[i]=1; return res; } /* Actual put of submatrix */ DYMOLA_STATIC void StringToSub(StringArray to,SizeType to_offset,SizeType to_dim, const StringArray from,SizeType from_offset,SizeType from_dim, SizeType trailingsize, struct TaggedIndexStack*ap) { Integer tag; if (!ap) return; /* Error */ tag=ap->tag; switch(tag) { case Colon: { SizeType newdim=from.dims[from_dim]; SizeType i; for(i=0;i<newdim;i++) StringToSub(to,to_offset*newdim+i, to_dim+1,from,from_offset*newdim+i,from_dim+1, trailingsize,ap+1); break; } case Range:case RangeRange: { Integer start,stop,stride=1,i,from_newdim,to_newdim; start=ap->u.range[0]; if (tag==RangeRange) stride=ap->u.range[1]; stop=ap->u.range[2]; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<from_newdim;i++) StringToSub(to,to_offset*to_newdim+(start+stride*i-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case Index: { Integer i=ap->u.index; StringToSub(to,to_offset*to.dims[to_dim]+(i-1),to_dim+1, from,from_offset,from_dim,trailingsize,ap+1); break; } case Vector: { IntegerArray v=ap->u.vector; Integer from_newdim,to_newdim,i; from_newdim=from.dims[from_dim]; to_newdim=to.dims[to_dim]; for(i=0;i<v.dims[0];i++) StringToSub(to,to_offset*to_newdim+(v.data[i]-1),to_dim+1, from,from_offset*from_newdim+i,from_dim+1, trailingsize,ap+1); break; } case EndMark: { SizeType i; String *to_p=to.data+to_offset; String *from_p=from.data+from_offset; for(i=0;i<trailingsize;i++,to_p+=1,from_p+=1) *to_p=*from_p; break; } } } /* Use as: StringGetSub(a,Colon,Index,3,Range,3,4,EndMark)=a[:,3,3:4] */ DYMOLA_STATIC StringArray StringGetSub(const StringArray a,...) { StringArray temp; va_list ap; SizeType ndims=a.ndims,trailingsize=1,nargs=0; /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,a); for(;!over;) { Integer tag=va_arg(ap,Integer); switch (tag) { case Colon:nargs++;break; case RangeRange:va_arg(ap,Integer); /* Fallthru*/ case Range:va_arg(ap,Integer),va_arg(ap,Integer);nargs++;break; case Vector:va_arg(ap,StringArray);nargs++;break; case Index:va_arg(ap,Integer);Assert(ndims>0,"Internal error in subscriptring of array");ndims--;nargs++;break; case EndMark:over=1;break; } } va_end(ap); Assert(nargs<=a.ndims,"Too many subscripts for array"); } temp.ndims=ndims; temp.dims=SizeTemp(ndims); /* Pass 2. Determine size of output */ { Integer over=0; SizeType temp_dim=0,a_dim=0; va_start(ap,a); for(;!over;) { Integer tag=va_arg(ap,Integer); switch (tag) { case Colon:temp.dims[temp_dim]=a.dims[a_dim];temp_dim++;break; case RangeRange:case Range: { Integer start,stop,stride=1,num; start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=1+(stop-start)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=a.dims[a_dim]),"Range subscripting: start out of range"); Assert((stop >=1)&&(stop <=a.dims[a_dim]),"Range subscripting: end out of range"); } temp.dims[temp_dim]=num; temp_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(v.ndims==1,"Array subscripting: only vectors (and scalars) allowed as indicies"); temp.dims[temp_dim]=v.dims[0]; for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=a.dims[a_dim]),"Array subscripting: vector index out of range"); } temp_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert((i>=1)&&(i<=a.dims[a_dim]),"Array subscripting: scalar index out of range"); break; } case EndMark:over=1;break; } a_dim++; } va_end(ap); { SizeType i; for(i=nargs;i<a.ndims;i++) { temp.dims[temp_dim++]=a.dims[i]; trailingsize*=a.dims[i]; } } } temp.data=StringTemp(CommonNrElements(temp.ndims, temp.dims)); /* Pass 3. Copy output */ { String *data=temp.data; struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,a); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); StringFromSub(temp,0,0,a,0,0,trailingsize,apt); } return temp; } /* Use as StringPutSub(a, out,Index,3,Colon,Range,3,4) yields out[3,:,3:4]=a; */ DYMOLA_STATIC StringArray StringCopy(const StringArray a) { int i,imax; StringArray temp; temp.ndims=a.ndims; temp.dims=SizeTemp(a.ndims); for(i=0;i<a.ndims;++i) temp.dims[i]=a.dims[i]; imax=StringNrElements(a); temp.data=StringTemp(imax); for(i=0;i<imax;++i) temp.data[i]=a.data[i]; return temp; } DYMOLA_STATIC void StringPutSub(const StringArray ain,StringArray out,...) { StringArray a; va_list ap; SizeType out_dim=0,a_dim=0,trailingsize=1,nargs=0; a=StringCopy(ain); /* Pass 1. Determine nr. dimensions of output */ { Integer over=0; va_start(ap,out); for(;!over;) { enum Subtag tag=va_arg(ap,int); switch (tag) { case Colon: Assert(out_dim<out.ndims,"Internal error in subscripting (:)"); Assert(a_dim<a.ndims,"Internal error in subscripting (:)"); Assert(out.dims[out_dim]==a.dims[a_dim],"Assignment array subscripting: A[:]=B must have identical sizes"); out_dim++; a_dim++; break; case RangeRange:case Range: { Integer start,stop,stride=1,num; Assert(out_dim<out.ndims,"Internal error in subscripting: range"); Assert(a_dim<a.ndims,"Internal error in subscripting: range "); start=va_arg(ap,Integer); if (tag==RangeRange) stride=va_arg(ap,Integer); stop=va_arg(ap,Integer); num=(stop-start+stride)/stride; if (num<=0) num=0; else { Assert((start>=1)&&(start<=out.dims[out_dim]),"Assignment array subscripting: start of range out of bounds"); Assert((stop>=1)&&(stop<=out.dims[out_dim]),"Assignment array subscripting: end of range out of bounds"); } Assert(a.dims[a_dim]==num,"Assignment array subscripting: A[a:b]=B must have identical sizes"); out_dim++; a_dim++; break; } case Vector: { IntegerArray v=va_arg(ap,IntegerArray); SizeType i; Assert(out_dim<out.ndims,"Internal error in vector subscripting"); Assert(a_dim<a.ndims,"Internal error in vector subscripting"); Assert(v.ndims==1,"Assignment array subscripting: array index must be a vector"); Assert(a.dims[a_dim]==v.dims[0],"Assignment array subscripting: A[vect]=B must have identical sizes"); for(i=0;i<v.dims[0];i++) { Assert((v.data[i]>=1)&&(v.data[i]<=out.dims[out_dim]),"Assignment array subscripting: vector index out of bounds"); } out_dim++; a_dim++; break; } case Index: { Integer i=va_arg(ap,Integer); Assert(out_dim<out.ndims,"Internal error in scalar subscripting"); Assert((i>=1)&&(i<=out.dims[out_dim]),"Assignment array subscripting: scalar index out of bounds"); out_dim++; break; } case EndMark:over=1;break; } } va_end(ap); Assert(a.ndims-a_dim==out.ndims-out_dim,"Assignment array subscripting: unequal number of dimensions"); { SizeType i; for(i=a_dim;i<a.ndims;i++) { trailingsize*=a.dims[i]; Assert(a.dims[i]==out.dims[(i-a_dim)+out_dim],"Internal error in subscripting"); } } } /* Pass 2. Copy output */ { struct TaggedIndexStack*apt=0; struct TaggedIndexStack VA_handler[100]; va_start(ap,out); apt=HandleVaList(ap, VA_handler, sizeof(VA_handler)/sizeof(*VA_handler)); va_end(ap); StringToSub(out,0,0,a,0,0,trailingsize,apt); } } /* For each operation Op(...) we create a temporary result res */ /* and call OpAssign(res,...) */ /* The operations Op(...) are convenient and used in the code */ /* Fill */ DYMOLA_STATIC StringArray StringFillAssign(StringArray res,const char* t) { SizeType i,prodsize; prodsize=StringNrElements(res); for(i=0;i<prodsize;i++) res.data[i]=t; return res; } DYMOLA_STATIC StringArray StringFill(const char* t,SizeType ndims,...) { va_list ap; StringArray temp; va_start(ap,ndims); temp=StringFillAssign(StringVaTemporary(ndims,ap),t); va_end(ap); return temp; } DYMOLA_STATIC StringArray StringFillArray(const StringArray a,SizeType ndims,...) { va_list ap; int i,j,inputProd,fillProd; StringArray temp; temp.ndims=a.ndims+ndims; temp.dims=SizeTemp(temp.ndims); va_start(ap,ndims); for(i=0;i<ndims;++i) temp.dims[i]=va_arg(ap,SizeType); va_end(ap); for(i=0;i<a.ndims;++i) temp.dims[i+ndims]=a.dims[i]; fillProd=1; for(i=0;i<ndims;++i) fillProd*=temp.dims[i]; inputProd=StringNrElements(a); temp.data=StringTemp(inputProd*fillProd); for(i=0;i<inputProd;++i) { for(j=0;j<fillProd;j++) { temp.data[i+j*inputProd]=a.data[i]; } } return temp; } DYMOLA_STATIC const char* Stringscalar(const StringArray a) { Assert(StringNrElements(a)==1,"scalar requires exactly one element"); return a.data[0]; } /* Matrix operations not limited to numeric matrices */ DYMOLA_STATIC StringArray Stringvector(const StringArray a) { StringArray res; #ifndef NDEBUG Integer i,found_non_one=0; for(i=0;i<a.ndims;i++) {if (a.dims[i]>1) {Assert(!found_non_one,"vector requires exactly one vector non-unit dimension");found_non_one=1;}} #endif res.ndims=1; res.dims=SizeTemp(1); res.dims[0]=StringNrElements(a); res.data=a.data; return res; } DYMOLA_STATIC StringArray Stringmatrix(const StringArray a) { StringArray res; res.ndims=2; res.dims=SizeTemp(2); res.dims[0]=a.dims[0]; res.dims[1]=(a.ndims<2)?1:a.dims[1]; res.data=a.data; Assert(StringNrElements(a)==StringNrElements(res),"matrix requires size(x,i)=1 for i>2"); return res; } DYMOLA_STATIC StringArray Stringtranspose(const StringArray a) { StringArray res; Integer i,j,k,remsize; res.ndims=a.ndims; Assert(a.ndims>=2,"transpose requires ndims>=2"); res.dims=SizeTemp(a.ndims); res.dims[0]=a.dims[1]; res.dims[1]=a.dims[0]; remsize=1; for(i=2;i<a.ndims;i++) { remsize*=(res.dims[i]=a.dims[i]); } res.data=StringTemp(CommonNrElements(res.ndims, res.dims)); for(i=0;i<res.dims[0];i++) for(j=0;j<res.dims[1];j++) { for(k=0;k<remsize;k++) { res.data[(i*res.dims[1]+j)*remsize+k]=a.data[(j*a.dims[1]+i)*remsize+k]; } } return res; } DYMOLA_STATIC StringArray Stringsymmetric(const StringArray a) { StringArray res; Integer i,j,n=a.dims[0]; Assert(a.ndims==2,"symmetric requires ndims==2"); Assert(a.dims[0]==a.dims[1],"symmetric requires square matrix"); res=StringTemporaryMatrix(n,n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) SetStringElement(StringElement(a,j,i),res,i,j); for(;j<=n;j++) SetStringElement(StringElement(a,i,j),res,i,j); } return res; } /* End of common routines for String*/ DYMOLA_STATIC Integer VectorWhenHandle(IntegerArray cond,IntegerArray eval,IntegerArray evalnew,Integer Event,Integer*AnyEvent) { /* Returns true if edge of any of the vector conditions.*/ Integer anyTrue=false; SizeType i,nrElem; Assert(IntegerMatchingSizes(cond,eval),"Internal error in array when."); nrElem=IntegerNrElements(cond); for(i=0;i<nrElem;i++) { if (cond.data[i]) { if (Event) { if (eval.data[i]) { anyTrue = true; *AnyEvent = true; evalnew.data[i] = false; } } } else { if (Event && !eval.data[i]) { /* *AnyEvent=true; */ } evalnew.data[i] = true; } } return anyTrue; } static void RealCopyMajor(RealArray to,SizeType to_offset,const RealArray x,SizeType from_offset,SizeType from_dist,SizeType dim) { if (dim>=x.ndims-1) { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) to.data[to_offset*imax+i]=x.data[from_offset+i*from_dist]; } else { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) RealCopyMajor(to,to_offset*imax+i,x,from_offset+i*from_dist,from_dist*imax,dim+1); } } DYMOLA_STATIC void RealSwitchMajorAssign(RealArray temp,const RealArray x) { RealCopyMajor(temp,0,x,0,1,0); } DYMOLA_STATIC RealArray RealSwitchMajor(const RealArray x) { if (x.ndims<=1) return x; { RealArray temp=RealMatch(x); {int i;for(i=0;i<x.ndims;i++) temp.dims[i]=x.dims[x.ndims-i-1]; /* Switch dimensions */} RealSwitchMajorAssign(temp,x); return temp; } } static void IntegerCopyMajor(IntegerArray to,SizeType to_offset,const IntegerArray x,SizeType from_offset,SizeType from_dist,SizeType dim) { if (dim>=x.ndims-1) { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) to.data[to_offset*imax+i]=x.data[from_offset+i*from_dist]; } else { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) IntegerCopyMajor(to,to_offset*imax+i,x,from_offset+i*from_dist,from_dist*imax,dim+1); } } DYMOLA_STATIC void IntegerSwitchMajorAssign(IntegerArray temp,const IntegerArray x) { IntegerCopyMajor(temp,0,x,0,1,0); } DYMOLA_STATIC IntegerArray IntegerSwitchMajor(const IntegerArray x) { if (x.ndims<=1) return x; {IntegerArray temp=IntegerMatch(x); {int i;for(i=0;i<x.ndims;i++) temp.dims[i]=x.dims[x.ndims-i-1]; /* Switch dimensions */} IntegerSwitchMajorAssign(temp,x); return temp; } } static void StringCopyMajor(StringArray to,SizeType to_offset,const StringArray x,SizeType from_offset,SizeType from_dist,SizeType dim) { if (dim>=x.ndims-1) { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) to.data[to_offset*imax+i]=x.data[from_offset+i*from_dist]; } else { SizeType i,imax=to.dims[dim]; for(i=0;i<imax;i++) StringCopyMajor(to,to_offset*imax+i,x,from_offset+i*from_dist,from_dist*imax,dim+1); } } DYMOLA_STATIC void StringSwitchMajorAssign(StringArray temp,const StringArray x) { StringCopyMajor(temp,0,x,0,1,0); } DYMOLA_STATIC StringArray StringSwitchMajor(const StringArray x) { if (x.ndims<=1) return x; {StringArray temp=StringMatch(x); {int i;for(i=0;i<x.ndims;i++) temp.dims[i]=x.dims[x.ndims-i-1]; /* Switch dimensions */} StringSwitchMajorAssign(temp,x); return temp; } } DYMOLA_STATIC RealArray RealLeading(int i,int j,RealArray a) { RealArray res; res.ndims=a.ndims-i; res.dims=a.dims+i; res.data=a.data+j*CommonNrElements(res.ndims, res.dims); return res; } DYMOLA_STATIC IntegerArray IntegerLeading(int i,int j,IntegerArray a) { IntegerArray res; res.ndims=a.ndims-i; res.dims=a.dims+i; res.data=a.data+j*CommonNrElements(res.ndims, res.dims); return res; } DYMOLA_STATIC StringArray StringLeading(int i,int j,StringArray a) { StringArray res; res.ndims=a.ndims-i; res.dims=a.dims+i; res.data=a.data+j*CommonNrElements(res.ndims, res.dims); return res; } #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) #include "amat.h" #include "sprwat.h" #endif DYMOLA_STATIC RealArray readMatrix(const char*fil,const char*matnam,Integer rows,Integer cols) { RealArray m=RealTemporaryMatrix(rows,cols); #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) Amatrix amatrix; AmatGetFile afile; int ret=amatGetOpen((char*)fil,"NoClass",(char*)0,&afile); int found=0; Assert(ret==0,amatError); for(;ret==0 && !found;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); Assert(ret<=1,amatError); if (ret<=1 && strcmp(matnam,amatrix.name)==0) { int i,j; Assert(rows==amatrix.nrow && cols==amatrix.ncol,"Matrix dimension incorrect"); Assert(amatrix.type==doubleMatrix || amatrix.type==realMatrix || amatrix.type==integerMatrix,"No string matrices allowed"); found=1; for(i=0;i<rows;i++) for(j=0;j<cols;j++) { double val=0; switch(amatrix.type) { case doubleMatrix:val=amatrix.data.d[i+j*rows];break; case realMatrix:val=amatrix.data.r[i+j*rows];break; case integerMatrix:val=amatrix.data.i[i+j*rows];break; default: break; } SetRealElement(val,m,i+1,j+1); } } amatDel(&amatrix); } amatGetClose(&afile); Assert(found, "Read of matrix failed"); #else Assert(false, "Cannot read files"); #endif return m; } DYMOLA_STATIC IntegerArray readMatrixSize(const char*fil,const char*matnam) { IntegerArray m=IntegerTemporaryVector(2); #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) Amatrix amatrix; AmatGetFile afile; int ret=amatGetOpen((char*)fil,"NoClass",(char*)0,&afile); int found=0; Assert(ret==0,amatError); for(;ret==0 && !found;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); Assert(ret<=1,amatError); if (ret<=1 && strcmp(matnam,amatrix.name)==0) { found=1; SetIntegerElement(amatrix.nrow,m,1); SetIntegerElement(amatrix.ncol,m,2); } amatDel(&amatrix); } amatGetClose(&afile); Assert(found, "Read of matrix failed"); #else Assert(false, "Cannot read files"); #endif return m; } DYMOLA_STATIC StringArray readMATmatrices_M(const char*fil) { StringArray s; #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) /* 1. Find number of matrices */ int nrMatrices=0,i=0; Amatrix amatrix; AmatGetFile afile; int ret=amatGetOpen((char*)fil,"NoClass",(char*)0,&afile); Assert(ret==0,amatError); for(;ret==0;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); if (ret<=1) ++nrMatrices; amatDel(&amatrix); } amatGetClose(&afile); s=StringFillAssign(StringTemporaryMatrix(nrMatrices,2), ""); ret=amatGetOpen((char*)fil,"NoClass",(char*)0,&afile); for(;ret==0;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); if (ret<=1) { char*s1=StringAllocate(strlen(amatrix.name)); const char*s2="Unknown"; strcpy(s1, amatrix.name); ++i; switch(amatrix.type) { case doubleMatrix:case realMatrix:s2="Real";break; case integerMatrix:s2="Integer";break; default:break; } SetStringElement(s1, s, i, 1); SetStringElement(s2, s, i, 2); } amatDel(&amatrix); } amatGetClose(&afile); #else Assert(false, "Cannot read files"); s = StringTemporaryVector(0); #endif return s; } DYMOLA_STATIC Real RealReadScalar(const char*fil,const char*matnam) { /* Modified 2008-06-11 Dan Henriksson Original implementation caused fatal error in VS 8 when compiling models for HILS on xPC */ /* return Realscalar(RealReadArray(fil,matnam,2)); */ RealArray m; Real val; #if defined(DYMOLA_DSPACE) || defined(NO_FILE) Assert(false, "Cannot read files"); m = RealTemporaryMatrix(0, 0); #else m = RealReadArray(fil,matnam,2); #endif val = Realscalar(m); return val; } DYMOLA_STATIC RealArray RealReadArray(const char*fil,const char*matnam,Integer ndims) { RealArray m; #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) Amatrix amatrix; AmatGetFile afile; char sizeName[200] = ""; int ret; int found, foundSize; Assert((ndims >= 1), "Current version can only read scalars, vectors, and matrices"); m.ndims = ndims; m.dims = SizeTemp(ndims); ret = amatGetOpen((char*)fil, "NoClass", (char*)0, &afile); found = 0; foundSize = 0; if (ndims > 2) { sprintfC(sizeName, "%s.size", matnam); } for(;ret==0 && !found;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); Assert(ret<=1,amatError); if (ret<=1 && strcmp(matnam,amatrix.name)==0) { int i,j,rows=amatrix.nrow,cols=amatrix.ncol; Assert(amatrix.type==doubleMatrix || amatrix.type==realMatrix || amatrix.type==integerMatrix,"No string matrices allowed"); found=1; m.data = RealTemp(rows*cols); if (!foundSize) { m.dims[0] = amatrix.nrow; m.dims[1] = amatrix.ncol; } for (i = 0; i < rows*cols; ++i) { double val = 0; switch (amatrix.type) { case doubleMatrix:val = amatrix.data.d[i]; break; case realMatrix:val = amatrix.data.r[i]; break; case integerMatrix:val = amatrix.data.i[i]; break; default: break; } m.data[i] = val; } } else if (ret <= 1 && ndims > 2 && !found && strcmp(sizeName, amatrix.name) == 0 && amatrix.nrow == ndims) { int i; Assert(amatrix.type == integerMatrix, "Integer matrix required"); for (i = 0; i < ndims; ++i) m.dims[i] = amatrix.data.i[i]; foundSize = 1; } amatDel(&amatrix); } amatGetClose(&afile); Assert(found, "Read of matrix failed"); if (ndims==1) return Realvector(m); #else Assert(false, "Cannot read files"); m = RealTemporaryMatrix(0, 0); #endif return m; } DYMOLA_STATIC Integer IntegerReadScalar(const char*fil,const char*matnam) { /* Modified 2008-06-11 Dan Henriksson Original implementation caused fatal error in VS 8 compiler for HILS on xPC */ /* return Integerscalar(IntegerReadArray(fil,matnam,2)); */ IntegerArray m; Integer val; #if defined(DYMOLA_DSPACE) || defined(NO_FILE) Assert(false, "Cannot read files"); m = IntegerTemporaryMatrix(0, 0); #else m = IntegerReadArray(fil,matnam,2); #endif val = Integerscalar(m); return val; } DYMOLA_STATIC IntegerArray IntegerReadArray(const char*fil,const char*matnam,Integer ndims) { IntegerArray m; #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) Amatrix amatrix; AmatGetFile afile; char sizeName[200] = ""; int ret; int found, foundSize; Assert((ndims >= 1), "Current version can only read scalars, vectors, and matrices"); m.ndims = ndims; m.dims = SizeTemp(ndims); ret = amatGetOpen((char*)fil, "NoClass", (char*)0, &afile); found = 0; foundSize = 0; if (ndims > 2) { sprintfC(sizeName, "%s.size", matnam); } for(;ret==0 && !found;) { amatInit(&amatrix); ret=amatGetMatrix(&afile, &amatrix); if (ret<=1 && strcmp(matnam,amatrix.name)==0) { int i,j,rows=amatrix.nrow,cols=amatrix.ncol; Assert(amatrix.type==integerMatrix,"Integer matrix required"); found=1; m.data = IntegerTemp(rows*cols); if (!foundSize) { m.dims[0] = amatrix.nrow; m.dims[1] = amatrix.ncol; } for (i = 0; i < rows*cols; ++i) { Integer val = 0; switch (amatrix.type) { case integerMatrix:val = amatrix.data.i[i]; break; default: break; } m.data[i] = val; } } else if (ret <= 1 && ndims > 2 && !found && strcmp(sizeName, amatrix.name) == 0 && amatrix.nrow == ndims) { int i; Assert(amatrix.type == integerMatrix, "Integer matrix required"); for (i = 0; i < ndims; ++i) m.dims[i] = amatrix.data.i[i]; foundSize = 1; } amatDel(&amatrix); } amatGetClose(&afile); Assert(found, "Read of matrix failed"); if (ndims==1) return Integervector(m); #else Assert(false, "Cannot read files"); m = IntegerTemporaryMatrix(0, 0); #endif return m; } DYMOLA_STATIC String StringReadScalar(const char*fil,const char*matnam) { /* Modified 2008-06-11 Dan Henriksson Original implementation caused fatal error in VS 8 compiler for HILS on xPC */ /* return Stringscalar(StringReadArray(fil,matnam,1)); */ StringArray m; String val; #if defined(DYMOLA_DSPACE) || defined(NO_FILE) Assert(false, "Cannot read files"); m = StringTemporaryVector(0); #else m = StringReadArray(fil,matnam,1); #endif val = Stringscalar(m); return val; } DYMOLA_STATIC StringArray StringReadArray(const char*fil,const char*matnam,Integer ndims) { StringArray m; #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) Amatrix amatrix; AmatGetFile afile; char sizeName[200] = ""; int ret; int found, foundSize; Assert((ndims >= 1), "Current version can only read scalars, vectors, and matrices"); m.ndims = ndims; m.dims = SizeTemp(ndims); ret = amatGetOpen((char*)fil, "NoClass", (char*)0, &afile); found = 0; foundSize = 0; if (ndims > 1) { sprintfC(sizeName, "%s.size", matnam); } Assert((ndims<=1)&&(ndims>=1),"Current version can only read scalars and vectors"); for(;ret==0 && !found;) { amatInit(&amatrix); ret=amatGetMatrixP3(&afile, &amatrix,voidMatrix,0,0); Assert(ret<=1,amatError); if (ret <= 1 && strcmp(matnam, amatrix.name) == 0) { int i, j, rows = amatrix.nrow; Assert(amatrix.type == charMatrix, "Only string matrices allowed"); found = 1; m.data = StringTemp(rows); if (!foundSize) { m.dims[0] = amatrix.nrow; } for (i = 0; i < rows; ++i) { #if defined(_MSC_VER) && _MSC_VER >= 1400 const char*val = amatrix.data.c[i] ? _strdup(amatrix.data.c[i]) : ""; #else const char*val = amatrix.data.c[i] ? strdup(amatrix.data.c[i]) : ""; #endif m.data[i] = val; } } else if (ret <= 1 && ndims > 1 && !found && strcmp(sizeName, amatrix.name) == 0 && amatrix.nrow == ndims) { int i; Assert(amatrix.type == integerMatrix, "Integer matrix required"); for (i = 0; i < ndims; ++i) m.dims[i] = amatrix.data.i[i]; foundSize = 1; } amatDel(&amatrix); } amatGetClose(&afile); Assert(found, "Read of matrix failed"); if (ndims==1) return Stringvector(m); #else Assert(false, "Cannot read files"); m = StringTemporaryVector(0); #endif return m; } #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) static void writeSize(AmatPutFile*file, int ndims, int sizes[], const char*name) { char sizename[200]; Amatrix sizeMatrix; sizeMatrix.ncol = 1; sizeMatrix.nrow = ndims; sizeMatrix.type = integerMatrix; sizeMatrix.data.i = sizes; sprintfC(sizename, "%s.size", name); sizeMatrix.name = sizename; amatPutMatrix(file, sizeMatrix); } #endif DYMOLA_STATIC void writeArrays(const char*fileName,int nargs,...) { #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) /* Format for ...: nargs copies of: const char*name,AmatType typ,int ndims,Array (RealArray etc) or scalar (Real, Integer,...) */ AmatPutFile file; va_list ap; if (amatPutOpen ((char*)fileName, amatBinary, binNormal, "", "", "", &file) != 0) { Assert(false,"failed to open output file"); } va_start(ap, nargs); for(;nargs>0;nargs--) { const char*matnam=va_arg(ap,const char*); Amatrix amatrix; int ret=100; amatrix.name=(char*)matnam; amatrix.nrow = amatrix.ncol = 1; { AmatType argtype = va_arg(ap, AmatType); int ndims = va_arg(ap, int); int tooLarge = ndims > 2 || ndims >= 2 && argtype == charMatrix; amatrix.type = argtype; if (ndims == 0) { switch (argtype) { case doubleMatrix: { Real x = va_arg(ap, Real); amatrix.data.d = &x; ret = amatPutMatrix(&file, amatrix); break; } case integerMatrix: { Integer x = va_arg(ap, Integer); amatrix.data.i = &x; ret = amatPutMatrix(&file, amatrix); break; } case charMatrix: { String x = va_arg(ap, String); amatrix.data.c = (char**)&x; ret = amatPutMatrixPadding(&file, amatrix, '\0'); break; } default: ; /* error */ } } else { MarkObject mark = PushMark(); switch (argtype) { case doubleMatrix: { RealArray x = va_arg(ap, RealArray); RealArray temp = x; amatrix.nrow = x.dims[0]; if (tooLarge) { amatrix.nrow = RealNrElements(x); writeSize(&file, ndims, x.dims, matnam); } else if (x.ndims > 1) amatrix.ncol = x.dims[1]; amatrix.data.d = (double*)temp.data; ret = amatPutMatrix(&file, amatrix); break; } case integerMatrix: { IntegerArray x = va_arg(ap, IntegerArray); IntegerArray temp = x; amatrix.nrow = x.dims[0]; if (tooLarge) { amatrix.nrow = IntegerNrElements(x); writeSize(&file, ndims, x.dims, matnam); } else if (x.ndims > 1) amatrix.ncol = x.dims[1]; amatrix.data.i = (Integer*)temp.data; ret = amatPutMatrix(&file, amatrix); break; } case charMatrix: { StringArray x = va_arg(ap, StringArray); StringArray temp = x; amatrix.nrow = x.dims[0]; if (tooLarge) { amatrix.nrow = StringNrElements(x); writeSize(&file, ndims, x.dims, matnam); } else if (x.ndims > 1) amatrix.ncol = x.dims[1]; amatrix.data.c = (char**)temp.data; ret = amatPutMatrix(&file, amatrix); break; } default: ; /* error */ } PopMark(mark); } } Assert(ret==0,"Write of matrix must succeed"); } va_end(ap); amatPutClose(&file); #else Assert(false, "Cannot write files"); #endif } DYMOLA_STATIC Integer writeMatrix(const char*fil,const char*matnam,const RealArray mat, int append) { int ret=1; #if !defined(DYMOLA_DSPACE) && !defined(NO_FILE) if (append) { int num=0,i; Amatrix amatOld[20]; AmatGetFile fileHandle; if ( amatGetOpen((char*)(fil), "NoClass", "0.0", &fileHandle ) == 0 ) { for (;num<19;) { amatInit(amatOld+num); if (amatGetMatrix(&fileHandle, amatOld+num) !=0) break; if (strcmp(amatOld[num].name,matnam)!=0) { num++; } else { amatDel(amatOld+num); } } amatGetClose(&fileHandle); } { MarkObject mark; RealArray temp; Amatrix amatrix; AmatPutFile filehandle; mark = PushMark(); temp = RealSwitchMajor(mat); amatrix.name = (char*) matnam; amatrix.nrow = mat.dims[0]; amatrix.ncol = mat.dims[1]; amatrix.type = doubleMatrix; amatrix.data.d = (double*) temp.data; amatrix.nrowallocated = 0; amatrix.nrowread = 0; if ( amatPutOpen ((char*)(fil), amatBinary,binNormal, "", "", "", &filehandle) != 0 ) ret=1; else { for(i=0;i<num;++i) { ret=amatPutMatrix(&filehandle,amatOld[i]); if (ret!=0) break; } if (ret==0) ret=amatPutMatrix(&filehandle,amatrix); amatPutClose(&filehandle); } for(i=0;i<num;++i) amatDel(amatOld+i); Assert(mat.ndims==2,"Only writing of matrices"); PopMark(mark); } } else { MarkObject mark; RealArray temp; Amatrix amatrix; mark = PushMark(); temp = RealSwitchMajor(mat); amatrix.name = (char*) matnam; amatrix.nrow = mat.dims[0]; amatrix.ncol = mat.dims[1]; amatrix.type = doubleMatrix; amatrix.data.d = (double*) temp.data; amatrix.nrowallocated = 0; amatrix.nrowread = 0; ret=amatWrite((char*)fil,amatBinary,amatrix); Assert(mat.ndims==2,"Only writing of matrices"); PopMark(mark); } #endif return ret==0; } /* Major pop, e.g. at end of integration */ DYMOLA_STATIC void PopMarkMarks() { EnsureMarkInitialized(); currentMark=startMark; stringmark=startstringmark; } DYMOLA_STATIC char* GetStringMark() { EnsureMarkInitialized(); return (char*)stringmark; } DYMOLA_STATIC void SetStringMark(char*s) { EnsureMarkInitialized(); if (s) stringmark=s; } DYMOLA_STATIC const char* SqueezeString(const char*s, char*startMarker) { EnsureMarkInitialized(); if (s>=startMarker && s<stringmark) { int len=strlen(s)+1; int i; if (s+len<=stringmark) { stringmark=startMarker+len; for(i=0;i<len;++i) startMarker[i]=s[i]; /* Might overlap*/ s=startMarker; } } else { stringmark=startMarker; } return s; } DYMOLA_STATIC String ConvertPointerToString(const char*a) { if (a) return a; else return ""; } DYMOLA_STATIC String ConvertToNonTempString(String s) { if (s>=startstringmark && s<Endsimplestring) { char*s2; SizeType len=0; int i; for(len=0;s[len]!=0;++len); Assert(startstringmarkNon+len+1<Endsimplestring,"Room to allocate string"); s2=startstringmarkNon; startstringmarkNon+=(len+1); for(i=0;i<=len;++i) s2[i]=s[i]; return s2; } return s; } DYMOLA_STATIC StringArray ConvertToNonTempStringArray(StringArray s) { StringArray s2; int len,i; s2=s; len=StringNrElements(s); for(i=0;i<len;++i) s2.data[i]=ConvertToNonTempString(s2.data[i]); return s2; } DYMOLA_STATIC char* StringAllocate(SizeType len) { char*ret=0; EnsureMarkInitialized(); ret=(char*)stringmark; Assert(stringmark+len+1<Endsimplestring,"Room to allocate string"); stringmark+=(len+1); return ret; } DYMOLA_STATIC String StringAdd(String a,String b) { char*ret=StringAllocate(strlen(a)+strlen(b)); strcpy(ret,a); strcat(ret,b); return ret; } DYMOLA_STATIC String Real2String(Real x,Integer minwidth,Integer precision) { char buf[100]; char*ret; Assert(precision<40 && minwidth<40,""); sprintf(buf,"%*.*g",(int)minwidth,(int)precision,(double)x); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC String Integer2String(Integer x,Integer minwidth,Integer precision) { char buf[100]; char*ret; Assert(precision<40 && minwidth<40,""); sprintf(buf,"%*.*d",(int)minwidth,(int)precision,(int)x); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC String Real2String3(Real x,Integer leftJustified,Integer minwidth,Integer precision) { char buf[100]; char*ret; Assert(precision<40 && minwidth<40,""); sprintf(buf,leftJustified?"%-*.*g":"%*.*g",(int)minwidth,(int)precision,(double)x); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC String Real2String2(Real x,Integer leftJustified,Integer minwidth) { return Real2String3(x,leftJustified,minwidth,6); } DYMOLA_STATIC String Integer2String2(Integer x,Integer leftJustified,Integer minwidth) { char buf[100]; char*ret; Assert(minwidth<40,""); sprintf(buf,leftJustified?"%-*d":"%*d",(int)minwidth,(int)x); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC String Boolean2String2(Integer x,Integer leftJustified,Integer minwidth) { char buf[100]; char*ret; Assert(minwidth<40,""); sprintf(buf,leftJustified?"%-*s":"%*s",(int)minwidth,x?"true":"false"); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC String Real2StringFormat(Real x,String s) { char buf[100]; char*ret; buf[99]='\0'; sprintf(buf,StringAdd("%",s),x); Assert(buf[99]=='\0',""); ret=StringAllocate(strlen(buf)); strcpy(ret,buf); return ret; } DYMOLA_STATIC void CopySlice(Real*x,RealArray y) { SizeType nrElem=RealNrElements(y); int i; for(i=0;i<nrElem;++i) x[i]=y.data[i]; return; } DYMOLA_STATIC RealArray RealTemporaryDense(Real*d,SizeType ndims,...) { RealArray temp; va_list ap; va_start(ap,ndims); temp=RealVaTemporarySize(ndims,ap); va_end(ap); temp.data=d; return temp; } DYMOLA_STATIC StringArray StringTemporaryDense(String*d,SizeType ndims,...) { StringArray temp; va_list ap; va_start(ap,ndims); temp=StringVaTemporarySize(ndims,ap); va_end(ap); temp.data=d; return temp; } DYMOLA_STATIC IntegerArray IntegerTemporaryDense(Real*d,SizeType ndims,...) { IntegerArray temp; int i,nrElem; va_list ap; va_start(ap,ndims); temp=IntegerVaTemporary(ndims,ap); va_end(ap); nrElem=IntegerNrElements(temp); for(i=0;i<nrElem;++i) temp.data[i]=(Integer)(d[i]); return temp; } DYMOLA_STATIC IntegerArray IntegerTemporaryDenseOrig(Integer*d,SizeType ndims,...) { IntegerArray temp; va_list ap; va_start(ap,ndims); temp=IntegerVaTemporarySize(ndims,ap); va_end(ap); temp.data=d; return temp; } DYMOLA_STATIC void ModelicaError(const char *string) { DymosimError((string)); } DYMOLA_STATIC void ModelicaFormatError(const char *string,...) { char buf[4000]; va_list ap; va_start(ap,string); #if defined(__WATCOMC__) && defined(DynSimStruct) || defined(NO_FILE) || defined(DYMOLA_DSPACE) strcpy(buf,string); #elif defined(_MSC_VER) && _MSC_VER>=1200 _vsnprintf(buf,sizeof(buf)/sizeof(*buf),string,ap); #else vsprintf(buf,string,ap); #endif va_end(ap); DymosimError(buf); } DYMOLA_STATIC void DymosimMessageNoNL(const char*); DYMOLA_STATIC void ModelicaMessage(const char *string) { DymosimMessageNoNL(string); } DYMOLA_STATIC void ModelicaFormatMessage(const char *string,...) { char buf[4000]; va_list ap; va_start(ap,string); #if defined(__WATCOMC__) && defined(DynSimStruct) || defined(NO_FILE) || defined(DYMOLA_DSPACE) strcpy(buf,string); #elif defined(_MSC_VER) && _MSC_VER>=1200 _vsnprintf(buf,sizeof(buf)/sizeof(*buf),string,ap); #else vsprintf(buf,string,ap); #endif va_end(ap); DymosimMessageNoNL(buf); } DYMOLA_STATIC char* ModelicaAllocateString(size_t len) { char*s=StringAllocate(len); s[len]='\0'; return s; } DYMOLA_STATIC char* ModelicaAllocateStringWithErrorReturn(size_t len) { EnsureMarkInitialized(); if (stringmark+len+1<Endsimplestring) return ModelicaAllocateString(len); else return 0; } DYMOLA_STATIC char* ModelicaDuplicateString(const char*str) { char*s = 0; if (str == 0) ModelicaFormatError("ModelicaDuplicateString with null-pointer"); else { s = StringAllocate(strlen(str) + 1); strcpy(s, str); } return s; } DYMOLA_STATIC char* ModelicaDuplicateStringWithErrorReturn(const char*str) { EnsureMarkInitialized(); if (str && (stringmark + strlen(str) + 1<Endsimplestring)) return ModelicaDuplicateString(str); else return 0; } DYMOLA_STATIC IntegerArray ANDArray(const IntegerArray a,const IntegerArray b) { SizeType prodsize,i; IntegerArray res=IntegerMatch(a); Assert(IntegerMatchingSizes(a,b),"and of arrays require arguments of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i] && b.data[i]; return res; } DYMOLA_STATIC IntegerArray ORArray(const IntegerArray a,const IntegerArray b) { SizeType prodsize,i; IntegerArray res=IntegerMatch(a); Assert(IntegerMatchingSizes(a,b),"or of arrays require arguments of matching size"); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=a.data[i] || b.data[i]; return res; } DYMOLA_STATIC IntegerArray NOTArray(const IntegerArray a) { SizeType prodsize,i; IntegerArray res=IntegerMatch(a); prodsize=IntegerNrElements(a); for(i=0;i<prodsize;i++) res.data[i]=!a.data[i]; return res; } #if defined(LIBDS_EXPORTS) || defined(LIBDSDLL_EXPORTS) /*TODO: can it really be excluded for Windows? */ #if !defined(_MSC_VER) || defined(__MINGW32__) #include "localeless.cpp" #endif #else #include "localeless.cpp" #endif #endif #if defined(_MSC_VER) #if !DymolaGlobalOptimizations_ /* Reset optimization to compiler switches */ #pragma optimize( "", on ) #endif #endif #endif
GB_binop__eq_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__eq_uint32) // A.*B function (eWiseMult): GB (_AemultB_01__eq_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__eq_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__eq_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__eq_uint32) // A*D function (colscale): GB (_AxD__eq_uint32) // D*A function (rowscale): GB (_DxB__eq_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__eq_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__eq_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__eq_uint32) // C=scalar+B GB (_bind1st__eq_uint32) // C=scalar+B' GB (_bind1st_tran__eq_uint32) // C=A+scalar GB (_bind2nd__eq_uint32) // C=A'+scalar GB (_bind2nd_tran__eq_uint32) // C type: bool // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x == y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_EQ || GxB_NO_UINT32 || GxB_NO_EQ_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__eq_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__eq_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__eq_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__eq_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__eq_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__eq_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__eq_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__eq_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__eq_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__eq_uint32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__eq_uint32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = (x == bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__eq_uint32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = (aij == y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB (_bind1st_tran__eq_uint32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB (_bind2nd_tran__eq_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tinyexr.h
/* Copyright (c) 2014 - 2019, Syoyo Fujita and many contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Syoyo Fujita nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic 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 // OWNER 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. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_THREAD #define TINYEXR_USE_THREAD (0) // No threaded loading. // http://computation.llnl.gov/projects/floating-point-compression #endif #ifndef TINYEXR_USE_OPENMP #ifdef _OPENMP #define TINYEXR_USE_OPENMP (1) #else #define TINYEXR_USE_OPENMP (0) #endif #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-6) #define TINYEXR_ERROR_CANT_OPEN_FILE (-7) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-8) #define TINYEXR_ERROR_INVALID_HEADER (-9) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-10) #define TINYEXR_ERROR_CANT_WRITE_FILE (-11) #define TINYEXR_ERROR_SERIALZATION_FAILED (-12) #define TINYEXR_ERROR_LAYER_NOT_FOUND (-13) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute *custom_attributes; // array of EXRAttribute. size = // `num_custom_attributes`. EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { For backward compatibility. Not recommended to use. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // Loads single-frame OpenEXR image by specifing layer name. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error // When the specified layer name is not found in the EXR file, the function will return `TINYEXR_ERROR_LAYER_NOT_FOUND`. extern int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layer_name, const char **err); // // Get layer infos from EXR file. // // @param[out] layer_names List of layer names. Application must free memory after using this. // @param[out] num_layers The number of layers // @param[out] err Error string(wll be filled when the function returns error code). Free it using FreeEXRErrorMessage after using this value. // // @return TINYEXR_SUCCEES upon success. // extern int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err); // @deprecated { to be removed. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Free's error message extern void FreeEXRErrorMessage(const char *msg); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> // #include <iostream> // debug #include <limits> #include <string> #include <vector> #if __cplusplus > 199711L // C++11 #include <cstdint> #if TINYEXR_USE_THREAD #include <atomic> #include <thread> #endif #endif // __cplusplus > 199711L #if TINYEXR_USE_OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #ifdef _MSC_VER #pragma warning(pop) #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif } // namespace miniz #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __GNUC__ #pragma GCC diagnostic pop #endif static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #endif static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { return false; } } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct HeaderInfo_t { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } } HeaderInfo; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString(&info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling)); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling)); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); (void)ret; assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4267) // 'argument': conversion from '__int64' to // 'int', possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressable run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wextra-semi-stmt") #pragma clang diagnostic ignored "-Wextra-semi-stmt" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<long long *> fHeap(HUF_ENCSIZE); *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode.data()); memcpy(frq, scode.data(), sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode >= ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; // begin unsigned short *oe = out + no; // end const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, raw->size(), raw->data()); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } std::vector<unsigned char> bitmap(BITMAP_SIZE); unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&maxNonZero, reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut.data(), &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * dst_num_lines * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * dst_width + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // // TODO(syoyo): Refactor function arguments. static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); if (!ret) { return false; } // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle( reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; // val = line_ptr[u]; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(hf.u), line_ptr + u); tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&val, line_ptr + u); tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } } return true; } static bool DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. return DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static bool ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { // ??? return false; } } return true; } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { if (err) { (*err) += "Failed to read attribute.\n"; } return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) += "Failed to parse channel info.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } } else { exr_header->custom_attributes = NULL; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size, std::string *err) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > threshold)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); int err_code = TINYEXR_SUCCESS; #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<size_t> tile_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_tiles)) { num_threads = int(num_tiles); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { size_t tile_idx = 0; while ((tile_idx = tile_count++) < num_tiles) { #else for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { #endif // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data size.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } size_t data_size = size_t(size - (offsets[tile_idx] + sizeof(int) * 5)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } if (tile_coordinates[3] != 0) { err_code = TINYEXR_ERROR_UNSUPPORTED_FEATURE; break; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { // TODO(LTE): atomic if (err) { (*err) += "Insufficient data length.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; break; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; bool ret = tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); if (!ret) { // TODO(LTE): atomic if (err) { (*err) += "Failed to decode tile data.\n"; } err_code = TINYEXR_ERROR_INVALID_DATA; } exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) } })); } // num_thread loop for (auto &t : workers) { t.join(); } #else } #endif if (err_code != TINYEXR_SUCCESS) { return err_code; } exr_image->num_tiles = static_cast<int>(num_tiles); } else { // scanline format // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void *) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) std::vector<std::thread> workers; std::atomic<int> y_count(0); int num_threads = std::max(1, int(std::thread::hardware_concurrency())); if (num_threads > int(num_blocks)) { num_threads = int(num_blocks); } for (int t = 0; t < num_threads; t++) { workers.emplace_back(std::thread([&]() { int y = 0; while ((y = y_count++) < int(num_blocks)) { #else #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { #endif size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_t(size - (offsets[y_idx] + sizeof(int) * 2)); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else if ((line_no > (2 << 20)) || (line_no < -(2 << 20))) { // Too large value. Assume this is invalid // 2**20 = 1048576 = heuristic value. invalid_data = true; } else if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example // `data_len < 4` invalid_data = true; } else { // line_no may be negative. int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { line_no -= exr_header->data_window[1]; } if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>( exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } #if (__cplusplus > 199711L) && (TINYEXR_USE_THREAD > 0) } })); } for (auto &t : workers) { t.join(); } #else } // omp parallel #endif } if (invalid_data) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 tinyexr::SetErrorMessage("Invalid data width value", err); return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data width or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if (data_width > threshold) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > threshold) { tinyexr::SetErrorMessage("data height too large.", err); return TINYEXR_ERROR_INVALID_DATA; } } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } #if 1 FreeEXRImage(exr_image); #else // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } #endif } return ret; } } static void GetLayers(const EXRHeader& exr_header, std::vector<std::string>& layer_names) { // Naive implementation // Group channels by layers // go over all channel names, split by periods // collect unique names layer_names.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string full_name(exr_header.channels[c].name); const size_t pos = full_name.find_last_of('.'); if (pos != std::string::npos && pos != 0 && pos + 1 < full_name.size()) { full_name.erase(pos); if (std::find(layer_names.begin(), layer_names.end(), full_name) == layer_names.end()) layer_names.push_back(full_name); } } } struct LayerChannel { explicit LayerChannel (size_t i, std::string n) : index(i) , name(n) {} size_t index; std::string name; }; static void ChannelsInLayer(const EXRHeader& exr_header, const std::string layer_name, std::vector<LayerChannel>& channels) { channels.clear(); for (int c = 0; c < exr_header.num_channels; c++) { std::string ch_name(exr_header.channels[c].name); if (layer_name.empty()) { const size_t pos = ch_name.find_last_of('.'); if (pos != std::string::npos && pos < ch_name.size()) { ch_name = ch_name.substr(pos + 1); } } else { const size_t pos = ch_name.find(layer_name + '.'); if (pos == std::string::npos) continue; if (pos == 0) { ch_name = ch_name.substr(layer_name.size() + 1); } } LayerChannel ch(size_t(c), ch_name); channels.push_back(ch); } } } // namespace tinyexr int EXRLayers(const char *filename, const char **layer_names[], int *num_layers, const char **err) { EXRVersion exr_version; EXRHeader exr_header; InitEXRHeader(&exr_header); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } std::vector<std::string> layer_vec; tinyexr::GetLayers(exr_header, layer_vec); (*num_layers) = int(layer_vec.size()); (*layer_names) = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(layer_vec.size()))); for (size_t c = 0; c < static_cast<size_t>(layer_vec.size()); c++) { #ifdef _MSC_VER (*layer_names)[c] = _strdup(layer_vec[c].c_str()); #else (*layer_names)[c] = strdup(layer_vec[c].c_str()); #endif } FreeEXRHeader(&exr_header); return TINYEXR_SUCCESS; } int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { return LoadEXRWithLayer(out_rgba, width, height, filename, /* layername */NULL, err); } int LoadEXRWithLayer(float **out_rgba, int *width, int *height, const char *filename, const char *layername, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to open EXR file or read version info from EXR file. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } // TODO: Probably limit loading to layers (channels) selected by layer index { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; std::vector<std::string> layer_names; tinyexr::GetLayers(exr_header, layer_names); std::vector<tinyexr::LayerChannel> channels; tinyexr::ChannelsInLayer(exr_header, layername == NULL ? "" : std::string(layername), channels); if (channels.size() < 1) { tinyexr::SetErrorMessage("Layer Not Found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_LAYER_NOT_FOUND; } size_t ch_count = channels.size() < 4 ? channels.size() : 4; for (size_t c = 0; c < ch_count; c++) { const tinyexr::LayerChannel &ch = channels[c]; if (ch.name == "R") { idxR = int(ch.index); } else if (ch.name == "G") { idxG = int(ch.index); } else if (ch.name == "B") { idxB = int(ch.index); } else if (ch.name == "A") { idxA = int(ch.index); } } if (channels.size() == 1) { int chIdx = int(channels.front().index); // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[chIdx][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[chIdx][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // Assume RGB(A) if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return ret; } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { tinyexr::SetErrorMessage(err_str, err); } } ConvertHeader(exr_header, info); // transfoer `tiled` from version. exr_header->tiled = version->tiled; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { std::stringstream ss; ss << "Failed to parse EXR version. code(" << ret << ")"; tinyexr::SetErrorMessage(ss.str(), err); return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } } else { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); return 0; } } #endif std::vector<unsigned char> memory; // Header { const char header[] = {0x76, 0x2f, 0x31, 0x01}; memory.insert(memory.end(), header, header + 4); } // Version, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // TOOD(LTE): C++11 thread // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #if TINYEXR_USE_OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // line_ptr[x] = val; tinyexr::cpy2(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 8192 + static_cast<unsigned int>( 2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } size_t totalSize = static_cast<size_t>(offset); { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } if (memory.size() == 0) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!fp)) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { tinyexr::SetErrorMessage("Invalid magic number", err); return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh)); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&h)); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { tinyexr::SetErrorMessage("Unsupported compression format", err); return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->num_tiles = 0; } void FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } free(exr_image->tiles); } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } int ret = SaveEXRImageToFile(&image, &header, outfilename, err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
assertok_error.c
/* case from t-cricial */ #include <stdio.h> #include <stdlib.h> #include <omp.h> #pragma omp declare target const int bs = 1024; const int nb = 128; #pragma omp end declare target const int X_VAL = 99; const int Y_VAL = 11; int main() { int failures = 0; long cpuExec = 0; #pragma omp target map(tofrom: cpuExec) { cpuExec = omp_is_initial_device(); } // Checking team-level swap doesn't currently work on host. if (!cpuExec) { // Initialise. int *x = (int*)malloc(sizeof(int)*nb); int *y = (int*)malloc(sizeof(int)*nb); for(int ii = 0; ii < nb; ++ii) { x[ii] = X_VAL; y[ii] = Y_VAL; } int failures=0; /// Test team-level dependencies with increment #pragma omp target map(tofrom: x[:nb], y[:nb]) #pragma omp teams num_teams(nb) thread_limit(bs) #pragma omp distribute parallel for for(int ii = 0; ii < nb*bs; ++ii) { #pragma omp critical { // Perform swap. const int temp = y[omp_get_team_num()]; y[omp_get_team_num()] = x[omp_get_team_num()] + 1; x[omp_get_team_num()] = temp; } } // Validate. failures = 0; const int xcheck = X_VAL + (bs/2); const int ycheck = Y_VAL + (bs/2); for(int ii = 0; ii < nb; ++ii) failures += (x[ii] != xcheck || y[ii] != ycheck); if(failures) printf("failed %d times\n", failures); else printf("Succeeded\n"); } else {// if !cpuExec printf("execution in CPU path\n"); } return failures?1:0; }
3d25pt_var.c
/* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 2048; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // 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; }
local_parametrization.h
#ifndef LOCAL_PARAMETRIZATION #define LOCAL_PARAMETRIZATION #include "defines.h" ///fitting //#include <vcg/space/fitting3.h> #include <vcg/math/matrix33.h> #include <vcg/space/triangle2.h> #include "texcoord_optimization.h" #include "mesh_operators.h" //#include <vcg/complex/algorithms/point_sampling.h> //#define samples_area 80 template <class MeshType> void ParametrizeExternal(MeshType &to_parametrize) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; std::vector<VertexType*> vertices; ///find first border vertex VertexType* Start=NULL; typename MeshType::VertexIterator Vi=to_parametrize.vert.begin(); while ((Start==NULL)&&(Vi<to_parametrize.vert.end())) { if (((*Vi).IsB())&&(!(*Vi).IsD())) Start=&(*Vi); Vi++; } if (Vi==to_parametrize.vert.end()) { assert(0); } ///get sorted border vertices FindSortedBorderVertices<MeshType>(to_parametrize,Start,vertices); //assert(vertices.size()>=4); ///find perimeter ScalarType perimeter=0; int size=vertices.size(); for (int i=0;i<size;i++) perimeter+=(vertices[i]->P()-vertices[(i+1)%size]->P()).Norm(); ///find scaling factor /*ScalarType Sperimeter=(2.0*M_PI)/perimeter;*/ ///set default texCoords for (Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { (*Vi).T().U()=-2; (*Vi).T().V()=-2; } ///set border vertices typename std::vector<VertexType*>::iterator iteV; /*ScalarType curr_perim=0;*/ ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle); vertices[0]->T().V()=sin(curr_angle); //for (int i=1;i<vertices.size();i++) //{ // curr_perim+=(vertices[i]->P()-vertices[(i-1)]->P()).Norm(); // //curr_perim+=perimeter/(ScalarType)size; // curr_angle=curr_perim*Sperimeter; // vertices[i]->T().U()=cos(curr_angle); // vertices[i]->T().V()=sin(curr_angle); // assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); // assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); //} ScalarType anglediv=(2.0*M_PI)/(ScalarType)(vertices.size()); curr_angle=0; for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=anglediv; vertices[i]->T().U()=cos(curr_angle); vertices[i]->T().V()=sin(curr_angle); assert((vertices[i]->T().U()>=-1)&&(vertices[i]->T().U()<=1)); assert((vertices[i]->T().V()>=-1)&&(vertices[i]->T().V()<=1)); } } template <class MeshType> void ParametrizeInternal(MeshType &to_parametrize) { typedef typename MeshType::ScalarType ScalarType; const ScalarType Eps=(ScalarType)0.0001; ///set internal vertices for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { //assert(!Vi->IsD()); if ((!Vi->IsB())&&(!Vi->IsD())) { ///find kernel std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); ScalarType kernel=0; for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); kernel+=(peso);//*dist); } assert(kernel>0); ///then find factor kernel=1.0/kernel; (*Vi).T().U()=0; (*Vi).T().V()=0; int num=0; ///find weighted media for (unsigned int k=0;k<star.size();k++) if (star[k]->IsB()) { ScalarType dist=((*Vi).P()-star[k]->P()).Norm(); if (dist<Eps) dist=Eps; //ScalarType peso=1.0/(dist); ScalarType peso=(dist)/star.size(); ScalarType kval=(peso)*kernel; assert(kval>0); (*Vi).T().U()+=kval*star[k]->T().U(); (*Vi).T().V()+=kval*star[k]->T().V(); num++; } ////on border case 2 neighbors ///go next to the center /*if (num==2) { (*Vi).T().U()/=2.0; (*Vi).T().V()/=2.0; }*/ /*ScalarType u=(*Vi).T().U(); ScalarType v=(*Vi).T().V();*/ assert(((*Vi).T().U()>=-1)&&((*Vi).T().U()<=1)); assert(((*Vi).T().V()>=-1)&&((*Vi).T().V()<=1)); } } ///smoothing of txcoords InitDampRestUV(to_parametrize); for (typename MeshType::VertexIterator Vi=to_parametrize.vert.begin();Vi!=to_parametrize.vert.end();Vi++) { if ((!Vi->IsB())&&(!Vi->IsD())) { std::vector<typename MeshType::VertexType*> star; getVertexStar<MeshType>(&(*Vi),star); vcg::Point2<ScalarType> UV=vcg::Point2<ScalarType>(0,0); for (unsigned int k=0;k<star.size();k++) UV+=star[k]->RestUV; UV/=(ScalarType)star.size(); (*Vi).T().P()=UV; } } } template <class FaceType> typename FaceType::CoordType InterpolatePos (FaceType* f, const typename FaceType::CoordType &bary) {return (f->V(0)->P()*bary.X()+f->V(1)->P()*bary.Y()+f->V(2)->P()*bary.Z());} template <class FaceType> typename FaceType::CoordType InterpolateRPos (FaceType* f,const typename FaceType::CoordType &bary) { return (f->V(0)->RPos*bary.X()+f->V(1)->RPos*bary.Y()+f->V(2)->RPos*bary.Z()); } template <class FaceType> typename FaceType::CoordType InterpolateNorm (FaceType* f, const typename FaceType::CoordType &bary) { typedef typename FaceType::CoordType CoordType; CoordType n0=f->V(0)->N(); CoordType n1=f->V(1)->N(); CoordType n2=f->V(2)->N(); return (n0*bary.X()+n1*bary.Y()+n2*bary.Z()); } template <class ScalarType> int Approx(const ScalarType &value) { ScalarType val0=floor(value); ScalarType val1=ceil(value); if (fabs(val0-value)<fabs(val1-value)) return ((int)val0); else return ((int)val1); } template <class FaceType> vcg::Point3i InterpolateColor (FaceType* f,const typename FaceType::CoordType &bary) { typedef typename FaceType::ScalarType ScalarType; vcg::Color4b c0=f->V(0)->C(); vcg::Color4b c1=f->V(1)->C(); vcg::Color4b c2=f->V(2)->C(); double R=(ScalarType)c0.X()*bary.X()+(ScalarType)c1.X()*bary.Y()+(ScalarType)c2.X()*bary.Z(); double G=(ScalarType)c0.Y()*bary.X()+(ScalarType)c1.Y()*bary.Y()+(ScalarType)c2.Y()*bary.Z(); double B=(ScalarType)c0.Z()*bary.X()+(ScalarType)c1.Z()*bary.Y()+(ScalarType)c2.Z()*bary.Z(); vcg::Point3i p=vcg::Point3i(Approx(R),Approx(G),Approx(B)); assert(p.X()<=255); assert(p.Y()<=255); assert(p.Z()<=255); return (p); } template <class VertexType> typename VertexType::CoordType ProjectPos(const VertexType &v) { typedef typename VertexType::FaceType FaceType; typedef typename VertexType::CoordType CoordType; FaceType *f=v.father; CoordType b=v.Bary; return (InterpolatePos<FaceType>(f,b)); } template <class VertexType> typename VertexType::CoordType Warp(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->P(0)*v->Bary.X()+father->P(1)*v->Bary.Y()+father->P(2)*v->Bary.Z(); return proj; } template <class VertexType> typename VertexType::CoordType WarpRpos(const VertexType* v) { typename VertexType::FaceType * father=v->father; typename VertexType::CoordType proj=father->V(0)->RPos*v->Bary.X()+father->V(1)->RPos*v->Bary.Y()+father->V(2)->RPos*v->Bary.Z(); return proj; } template <class MeshType> typename MeshType::ScalarType EstimateLenghtByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; // assert((on_edge.size()==0)||(on_edge.size()==1)); ScalarType estimated[2]={0,0}; size_t num[2]={0,0}; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; int edge_index=EdgeIndex(test_face,v0,v1); FaceType *Fopp=test_face->FFp(edge_index); if (test_face->vertices_bary.size()<2) { ScalarType dist=Distance(v0->RPos,v1->RPos); //#pragma omp atomic estimated[i]+=dist; num[i]=0; continue; } ///collect vertices std::vector<VertexType*> vertices; vertices.reserve(test_face->vertices_bary.size()); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) vertices.push_back(test_face->vertices_bary[k].first); ///collect faces std::vector<FaceType*> faces; getSharedFace<MeshType>(vertices,faces); ///get border edges std::vector<std::pair<VertexType*,VertexType*> > edges; for (unsigned int j=0;j<faces.size();j++) { FaceType*f=faces[j]; ///find if there is an on-edge edge bool found=false; int k=0; while ((k<3)&&(!found)) { if ((f->V0(k)->father==test_face)&& (f->V1(k)->father==test_face)&& (f->V2(k)->father==Fopp)) { edges.push_back(std::pair<VertexType*,VertexType*>(f->V0(k),f->V1(k))); found=true; } k++; } } ///find if there's ant edge return inital lenght if (edges.size()==0) { estimated[i]+=(Distance(v0->RPos,v1->RPos)); num[i]=0; continue; } else { //get edge direction ///store the two nearest for each vertex /*VertexType *n0=edges[0].first; VertexType *n1=edges[0].second; ScalarType d0=(Warp(n0)-v0->P()).Norm(); ScalarType d1=(Warp(n1)-v1->P()).Norm();*/ //CoordType edgedir=v0->cP()-v1->cP(); CoordType edgedir=v0->RPos-v1->RPos; edgedir.Normalize(); num[i]=edges.size(); for (unsigned int e=0;e<edges.size();e++) { VertexType *vH0=edges[e].first; VertexType *vH1=edges[e].second; ///project points over the plane /*CoordType proj0=Warp(vH0); CoordType proj1=Warp(vH1);*/ CoordType proj0=WarpRpos(vH0); CoordType proj1=WarpRpos(vH1); CoordType dirproj=proj0-proj1; dirproj.Normalize(); //estimated[i]+=fabs(dirproj*edgedir)*((vH0->P()-vH1->P()).Norm()); //#pragma omp atomic estimated[i]+=fabs(dirproj*edgedir)*((vH0->RPos-vH1->RPos).Norm()); } } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num; if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; estimated[0]= (ScalarType)(alpha0*estimated[0]+(1.0-alpha0)*(Distance(v0->RPos,v1->RPos))); estimated[1]= (ScalarType)(alpha1*estimated[1]+(1.0-alpha1)*(Distance(v0->RPos,v1->RPos))); return(ScalarType)((estimated[0]+estimated[1])/2.0); } template <class MeshType> void MeanVal(const std::vector<vcg::Point2<typename MeshType::ScalarType> > &Points, std::vector<typename MeshType::ScalarType> &Lamda, typename MeshType::CoordType &p) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; int size=Points.size(); Lamda.resize(size); ScalarType sum=0; for (int i=0;i<size;i++) { int size=Points.size()-1; vcg::Point2<ScalarType> Pcurr=Points[i]; vcg::Point2<ScalarType> Pprev=Points[(i+(size-1))%size]; vcg::Point2<ScalarType> Pnext=Points[(i+1)%size]; CoordType v0=Pprev-p; CoordType v1=Pcurr-p; CoordType v2=Pnext-p; ScalarType l=v1.Norm(); v0.Normalize(); v1.Normalize(); v2.Normalize(); ScalarType Alpha0=acos(v0*v1); ScalarType Alpha1=acos(v1*v2); Lamda[i]=(tan(Alpha0/2.0)+tan(Alpha1/2.0))/l; sum+=Lamda[i]; } ///normalization for (int i=0;i<size;i++) Lamda[i]/=sum; } template <class FaceType> typename FaceType::ScalarType EstimateAreaByParam(const FaceType* f) { typedef typename FaceType::VertexType VertexType; typedef typename FaceType::ScalarType ScalarType; int num=0; ScalarType estimated=0; for (unsigned int k=0;k<f->vertices_bary.size();k++) { VertexType *HresVert=f->vertices_bary[k].first; estimated+=HresVert->area; num++; } ///media of estimated values ScalarType alpha; ScalarType max_num=abstraction_num; if (num>=max_num) alpha=1; else alpha=num/max_num; ScalarType Rarea= (ScalarType)(((f->cV(1)->RPos-f->cV(0)->RPos)^(f->cV(2)->RPos-f->cV(0)->RPos)).Norm()/2.0); estimated=(ScalarType)(alpha*estimated+(1.0-alpha)*Rarea); return(estimated); } template <class MeshType> typename MeshType::ScalarType EstimateAreaByParam (const typename MeshType::VertexType* v0, const typename MeshType::VertexType* v1, typename MeshType::FaceType* on_edge[2]) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; typedef typename MeshType::ScalarType ScalarType; //MeshType::PerVertexAttributeHandle<AuxiliaryVertData> handle = vcg::tri::Allocator<MeshType>::GetPerVertexAttribute<AuxiliaryVertData>(mesh,"AuxiliaryVertData"); ScalarType estimated[2]={0,0}; int num[2]={0,0}; VertexType *v2[2]; for (int i=0;i<2;i++) { FaceType *test_face=on_edge[i]; for (int k=0;k<3;k++) if ((test_face->V(k)!=v0)&&(test_face->V(k)!=v1)) v2[i]=test_face->V(k); for (unsigned int k=0;k<test_face->vertices_bary.size();k++) { VertexType *brother=test_face->vertices_bary[k].first; estimated[i]+=brother->area; //estimated[i]+=handle[brother].area; num[i]++; } } ///media of estimated values ScalarType alpha0,alpha1; ScalarType max_num=abstraction_num;//20 if (num[0]>=max_num) alpha0=1; else alpha0=num[0]/max_num; if (num[1]>=max_num) alpha1=1; else alpha1=num[1]/max_num; ScalarType Rarea0= (ScalarType)(((on_edge[0]->V(1)->RPos-on_edge[0]->V(0)->RPos)^(on_edge[0]->V(2)->RPos-on_edge[0]->V(0)->RPos)).Norm()/2.0); ScalarType Rarea1= (ScalarType)(((on_edge[1]->V(1)->RPos-on_edge[1]->V(0)->RPos)^(on_edge[1]->V(2)->RPos-on_edge[1]->V(0)->RPos)).Norm()/2.0); estimated[0]= (ScalarType)(alpha0*estimated[0]+(1.0-alpha0)*Rarea0); estimated[1]= (ScalarType)(alpha1*estimated[1]+(1.0-alpha1)*Rarea1); return(ScalarType)((estimated[0]+estimated[1])/2.0); } ///template class used to sample surface template <class FaceType> class VertexSampler{ typedef typename FaceType::CoordType CoordType; public: std::vector<CoordType> points; void AddFace(const FaceType &f,const CoordType & bary) {points.push_back(f.P(0)*bary.X()+f.P(1)*bary.Y()+f.P(2)*bary.Z());} }; ///sample 3d vertex possible's position ///using area criterion //template <class MeshType> //void SamplingPoints(MeshType &mesh, // std::vector<typename MeshType::CoordType> &pos) //{ // typedef typename MeshType::CoordType CoordType; // typedef VertexSampler<MeshType::FaceType> Sampler; // pos.reserve(samples_area); // Sampler ps; // ps.points.reserve(samples_area); // // vcg::tri::SurfaceSampling<MeshType,Sampler>::Montecarlo(mesh,ps,samples_area); // pos=std::vector<CoordType>(ps.points.begin(),ps.points.end()); //} template <class MeshType> void InitDampRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].RestUV=m.vert[i].T().P(); } template <class MeshType> void RestoreRestUV(MeshType &m) { for (unsigned int i=0;i<m.vert.size();i++) m.vert[i].T().P()=m.vert[i].RestUV; } #ifndef IMPLICIT ///parametrize a submesh from trinagles that are incident on vertices template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; //const ScalarType epsilon=(ScalarType)0.0001; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #else ///parametrize a submesh keeping fixed the borders template <class MeshType> void ParametrizeLocally(MeshType &parametrized, bool fix_boundary=true, bool init_border=true) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::CoordType CoordType; ///save old positions std::vector<CoordType> positions; positions.resize(parametrized.vert.size()); ///set rest position for (unsigned int i=0;i<parametrized.vert.size();i++) { positions[i]=parametrized.vert[i].P(); parametrized.vert[i].P()=parametrized.vert[i].RPos; } UpdateTopologies(&parametrized); if (init_border) ParametrizeExternal(parametrized); ParametrizeInternal(parametrized); //for (int i=0;i<parametrized.vert.size();i++) // parametrized.vert[i].RPos=parametrized.vert[i].P(); vcg::tri::MeanValueTexCoordOptimization<MeshType> opt(parametrized); vcg::tri::AreaPreservingTexCoordOptimization<MeshType> opt1(parametrized); opt.SetSpeed((ScalarType)0.0005); InitDampRestUV(parametrized); if (fix_boundary) { opt.TargetEquilateralGeometry(); //opt.TargetCurrentGeometry(); opt.SetBorderAsFixed(); opt.IterateUntilConvergence((ScalarType)0.000001,100); /*opt.Iterate(); opt.Iterate();*/ } else { opt1.TargetCurrentGeometry(); //opt1.SetBorderAsFixed(); opt1.IterateUntilConvergence((ScalarType)0.000001,200); } ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Triangle2<typename MeshType::ScalarType> t2d=vcg::Triangle2<typename MeshType::ScalarType>(tex0,tex1,tex2); #ifndef NDEBUG ScalarType area=(tex1-tex0)^(tex2-tex0); assert(area>0); #endif } ///restore position for (unsigned int i=0;i<parametrized.vert.size();i++) parametrized.vert[i].P()=positions[i]; } #endif template <class MeshType> void ForceInParam(vcg::Point2<typename MeshType::ScalarType> &UV,MeshType &domain) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; ScalarType minDist=(ScalarType)1000.0; vcg::Point2<ScalarType> closest; vcg::Point2<ScalarType> center=vcg::Point2<ScalarType>(0,0); for (unsigned int i=0;i<domain.face.size();i++) { FaceType *f=&domain.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); center+=tex0; center+=tex1; center+=tex2; vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType dist; vcg::Point2<ScalarType> temp; t2d.PointDistance(UV,dist,temp); if (dist<minDist) { minDist=dist; closest=temp; } } center/=(ScalarType)(domain.face.size()*3); UV=closest*(ScalarType)0.95+center*(ScalarType)0.05; } template <class VertexType> bool testParamCoords(VertexType *v) { typedef typename VertexType::ScalarType ScalarType; ScalarType eps=(ScalarType)0.00001; if (!(((v->T().P().X()>=-1-eps)&&(v->T().P().X()<=1+eps)&& (v->T().P().Y()>=-1-eps)&&(v->T().P().Y()<=1+eps)))) return (false); return true; } template <class MeshType> bool testParamCoords(MeshType &domain) { for (unsigned int i=0;i<domain.vert.size();i++) { typename MeshType::VertexType *v=&domain.vert[i]; bool b=testParamCoords<typename MeshType::VertexType>(v); if (!b) { #ifndef _MESHLAB printf("\n position %lf,%lf \n",v->T().U(),v->T().V()); #endif return false; } } return true; } template <class CoordType> bool testBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ///test float eps=(ScalarType)0.0001; if(!(fabs(bary.X()+bary.Y()+bary.Z()-1.0)<eps)) return false; if(!((bary.X()<=1.0)&&(bary.X()>=-eps)&&(bary.Y()<=1.0)&&(bary.Y()>=-eps)&&(bary.Z()<=1.0)&&(bary.Z()>=-eps))) return false; return true; } template <class CoordType> bool NormalizeBaryCoords(CoordType &bary) { typedef typename CoordType::ScalarType ScalarType; ScalarType EPS=(ScalarType)0.00000001; bool isOK=testBaryCoords(bary); if (!isOK) return false; typedef typename CoordType::ScalarType ScalarType; ///test <0 if (bary.X()<0) bary.X()=EPS; if (bary.Y()<0) bary.Y()=EPS; if (bary.Z()<0) bary.Z()=EPS; ///test >1 if (bary.X()>1.0) bary.X()=1.0-EPS; if (bary.Y()>1.0) bary.Y()=1.0-EPS; if (bary.Z()>1.0) bary.Z()=1.0-EPS; ///test sum ScalarType diff=bary.X()+bary.Y()+bary.Z()-1.0; bary.X()-=(diff+EPS); if (bary.X()<0) bary.X()=EPS; return true; } template <class MeshType> void AssingFather(typename MeshType::VertexType &v, typename MeshType::FaceType *father, typename MeshType::CoordType &bary, MeshType & domain) { #ifdef _DEBUG const typename MeshType::ScalarType eps=(typename MeshType::ScalarType)0.00001; assert(vcg::tri::IsValidPointer(domain,father)); assert(!(father->IsD())); assert(!(father==NULL)); assert((bary.X()>=0)&&(bary.X()<=1)&& (bary.Y()>=0)&&(bary.Y()<=1)&& (bary.Z()>=0)&&(bary.Z()<=1)&& ((bary.X()+bary.Y()+bary.Z())<=1+eps)&& ((bary.X()+bary.Y()+bary.Z())>=1-eps)); #endif v.father=father; v.Bary=bary; } template <class MeshType> bool testParametrization(MeshType &domain, MeshType &Hlev) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::VertexType VertexType; bool is_good=true; int num_del=0; int num_null=0; int fath_son=0; int wrong_address=0; for (unsigned int i=0;i<Hlev.vert.size();i++) { VertexType *v=&Hlev.vert[i]; bool isGoodAddr=true; if ((v->father-&(*domain.face.begin()))>=(int)domain.face.size()) { // printf("\n ADDRESS EXCEEDS OF %d \n",v->father-&(*domain.face.begin())); wrong_address++; is_good=false; isGoodAddr=false; } if ((isGoodAddr)&&(v->father==NULL)) { //printf("\n PAR ERROR : father NULL\n"); num_null++; is_good=false; } if ((isGoodAddr)&&(v->father->IsD())) { //printf("\n PAR ERROR : father DELETED \n"); num_del++; is_good=false; } if ((isGoodAddr)&&(!(((v->Bary.X()>=0)&&(v->Bary.X()<=1))&& ((v->Bary.Y()>=0)&&(v->Bary.Y()<=1))&& ((v->Bary.Z()>=0)&&(v->Bary.Z()<=1))))) { printf("\n PAR ERROR 0: bary coords exceeds: %f,%f,%f \n",v->Bary.X(),v->Bary.Y(),v->Bary.Z()); /*system("pause");*/ NormalizeBaryCoords(v->Bary); is_good=false; } } for (unsigned int i=0;i<domain.face.size();i++) { FaceType *face=&domain.face[i]; if (!face->IsD()) { for (unsigned int j=0;j<face->vertices_bary.size();j++) { VertexType *v=face->vertices_bary[j].first; if (v->father!=face) { //printf("\n PAR ERROR : Father<->son \n"); fath_son++; v->father=face; is_good=false; } } } } if (num_del>0) printf("\n PAR ERROR %d Father isDel \n",num_del); if (num_null>0) printf("\n PAR ERROR %d Father isNull \n",num_null); if (fath_son>0) printf("\n PAR ERROR %d Father<->son \n",fath_son); if (wrong_address>0) { printf("\n PAR ERROR %d Wrong Address Num Faces %d\n",wrong_address,domain.fn); /*system("pause");*/ } return (is_good); } template <class MeshType> bool NonFolded(MeshType &parametrized) { //const ScalarType epsilon=0.00001; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=0) return false; } } return true; } template <class MeshType> bool NonFolded(MeshType &parametrized,std::vector<typename MeshType::FaceType*> &folded) { typedef typename MeshType::FaceType FaceType; typedef typename MeshType::ScalarType ScalarType; const ScalarType epsilon=(ScalarType)0.00001; folded.resize(0); ///assert parametrization for (unsigned int i=0;i<parametrized.face.size();i++) { FaceType *f=&parametrized.face[i]; if (!((f->V(0)->IsB())&&(f->V(1)->IsB())&&(f->V(2)->IsB()))) { vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); ScalarType area=(tex1-tex0)^(tex2-tex0); if (area<=epsilon) folded.push_back(f); } } return (folded.size()==0); } //getFoldedFaces(std::vector) ///parametrize a submesh from trinagles that are incident on vertices with equi-area subdivision template <class MeshType> void ParametrizeStarEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &radius=1) { typedef typename MeshType::ScalarType ScalarType; typedef typename MeshType::VertexType VertexType; UpdateTopologies(&parametrized); //set borders ///find first border & non border vertex std::vector<VertexType*> non_border; VertexType* Start=NULL; for (unsigned int i=0;i<parametrized.vert.size();i++) { VertexType* vert=&parametrized.vert[i]; if ((Start==NULL)&&(vert->IsB())) Start=vert; if (!vert->IsB()) non_border.push_back(vert); } assert(non_border.size()!=0); ///get sorted border vertices std::vector<VertexType*> vertices; FindSortedBorderVertices<MeshType>(parametrized,Start,vertices); ///set border vertices int num=vertices.size(); typename std::vector<VertexType*>::iterator iteV; ScalarType curr_angle=0; vertices[0]->T().U()=cos(curr_angle)*radius; vertices[0]->T().V()=sin(curr_angle)*radius; ScalarType division=(2*M_PI)/(ScalarType)num; ///set border for (unsigned int i=1;i<vertices.size();i++) { curr_angle+=division; vertices[i]->T().U()=radius*cos(curr_angle); vertices[i]->T().V()=radius*sin(curr_angle); } if (non_border.size()==1) { ///if non-border vertex is one then set it to zero otherwise ///set it to the average of neighbors non_border[0]->T().P()=vcg::Point2<ScalarType>(0,0); } else { ///set media of star vertices assert(non_border.size()==2); for (unsigned int i=0;i<non_border.size();i++) { VertexType *v=non_border[i]; v->T().P()=vcg::Point2<ScalarType>(0,0); int ariety_vert=0; std::vector<VertexType*> star; getVertexStar<MeshType>(v,star); for (unsigned int k=0;k<star.size();k++) { if ((!star[k]->IsD())&&(star[k]->IsB())) { v->T().P()+=star[k]->T().P(); ariety_vert++; } } v->T().P()/=(ScalarType)ariety_vert; } ///test particular cases if (!NonFolded(parametrized)) { std::vector<VertexType*> shared; getSharedVertexStar<MeshType>(non_border[0],non_border[1],shared); assert(shared.size()==2); assert(shared[0]->IsB()); assert(shared[1]->IsB()); assert(shared[0]!=shared[1]); //ScalarType epsilon=(ScalarType)0.001; ///then get the media of two shared vertices vcg::Point2<ScalarType> uvAve=shared[0]->T().P()+shared[1]->T().P(); assert(uvAve.Norm()>(ScalarType)0.001); uvAve.Normalize(); vcg::Point2<ScalarType> p0=uvAve*(ScalarType)0.3; vcg::Point2<ScalarType> p1=uvAve*(ScalarType)(-0.3); ///then test and set right assignement non_border[0]->T().P()=p0; non_border[1]->T().P()=p1; if (!NonFolded(parametrized)){ non_border[0]->T().P()=p1; non_border[1]->T().P()=p0; } } } ///final assert parametrization assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeDiamondEquilateral(MeshType &parametrized, const int &edge0,const int &edge1, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::VertexType VertexType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *fd0=&parametrized.face[0]; #ifndef NDEBUG FaceType *fd1=&parametrized.face[1]; #endif assert(fd0->FFp(edge0)==fd1); assert(fd1->FFp(edge1)==fd0); ///get 2 vertex on the edge VertexType *v0=fd0->V(edge0); VertexType *v1=fd0->V((edge0+1)%3); #ifndef NDEBUG VertexType *vtest0=fd1->V(edge1); VertexType *vtest1=fd1->V((edge1+1)%3); assert(v0!=v1); assert(vtest0!=vtest1); assert(((v0==vtest0)&&(v1==vtest1))||((v1==vtest0)&&(v0==vtest1))); #endif ///other 2 vertex VertexType *v2=parametrized.face[0].V((edge0+2)%3); VertexType *v3=parametrized.face[1].V((edge1+2)%3); assert((v2!=v3)&&(v0!=v2)&&(v0!=v3)&&(v1!=v2)&&(v1!=v3)); ///assing texcoords v0->T().P()=vcg::Point2<ScalarType>(0,-edge_len/2.0); v1->T().P()=vcg::Point2<ScalarType>(0,edge_len/2.0); v2->T().P()=vcg::Point2<ScalarType>(-h,0); v3->T().P()=vcg::Point2<ScalarType>(h,0); ///test assert(NonFolded(parametrized)); } ///given the mesh and the two edges (same) seen from face[0] and face[1] of the mesh construct ///a diamond parametrization using equilateral triangles of edge edge_len template <class MeshType> void ParametrizeFaceEquilateral(MeshType &parametrized, const typename MeshType::ScalarType &edge_len=1) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::ScalarType ScalarType; ScalarType h=(sqrt(3.0)/2.0)*edge_len; FaceType *f_param=&(parametrized.face[0]); f_param->V(0)->T().P()=vcg::Point2<ScalarType>(edge_len/2.0,0); f_param->V(1)->T().P()=vcg::Point2<ScalarType>(0,h); f_param->V(2)->T().P()=vcg::Point2<ScalarType>(-edge_len/2.0,0); } ///parametrize and create a submesh from trinagles that are incident on /// vertices .... seturn a vetor of original faces template <class MeshType> void ParametrizeLocally(MeshType &parametrized, const std::vector<typename MeshType::VertexType*> &subset, std::vector<typename MeshType::FaceType*> &orderedFaces, std::vector<typename MeshType::VertexType*> &orderedVertex) { typedef typename MeshType::FaceType FaceType; typedef typename FaceType::VertexType VertexType; orderedFaces.clear(); std::vector<VertexType*> vertices; ///get faces referenced by vertices getSharedFace<MeshType>(subset,orderedFaces); ///do a first copy of the mesh ///and parametrize it ///NB: order of faces is mantained CopyMeshFromFaces<MeshType>(orderedFaces,orderedVertex,parametrized); //CreateMeshVertexStar(subset,orderedFaces,parametrized); ParametrizeLocally(parametrized); } template <class MeshType> void InterpolateUV(const typename MeshType::FaceType* f, const typename MeshType::CoordType &bary, typename MeshType::ScalarType &U, typename MeshType::ScalarType &V) { U=bary.X()*f->cV(0)->T().U()+bary.Y()*f->cV(1)->T().U()+bary.Z()*f->cV(2)->T().U(); V=bary.X()*f->cV(0)->T().V()+bary.Y()*f->cV(1)->T().V()+bary.Z()*f->cV(2)->T().V(); /*if ((!((U>=-1)&&(U<=1)))||(!((V>=-1)&&(V<=1)))) { printf("Bary:%f,%f,%f \n",bary.X(),bary.Y(),bary.Z()); printf("texCoord:%f,%f \n",U,V); assert(0); }*/ //assert ((U>=-1)&&(U<=1)); //assert ((V>=-1)&&(V<=1)); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &bary, int &index) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=bary[x]; } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; return true; } } return (false); } template <class FaceType> bool GetBaryFaceFromUV(std::vector<FaceType*> faces, const typename FaceType::ScalarType &U, const typename FaceType::ScalarType &V, typename FaceType::CoordType &bary, int &index) { typedef typename FaceType::ScalarType ScalarType; typedef typename FaceType::ScalarType ScalarType; const ScalarType _EPSILON = ScalarType(0.0000001); /*assert ((U>=-1)&&(U<=1)); assert ((V>=-1)&&(V<=1));*/ for (unsigned int i=0;i<faces.size();i++) { FaceType *f=faces[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->V(0)->T().U(),f->V(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->V(1)->T().U(),f->V(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->V(2)->T().U(),f->V(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=fabs((tex1-tex0)^(tex2-tex0)); //assert(area>-_EPSILON); ///then find if the point 2d falls inside if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { index=i; ///approximation errors ScalarType sum=0; for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; sum+=fabs(bary[x]); } if (sum==0) printf("error SUM %f \n",sum); bary/=sum; /*if (!((bary.X()>=0)&& (bary.X()<=1))) printf("error %f \n",bary.X());*/ /*ScalarType diff=(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff;*/ return true; } } return (false); } template <class MeshType> bool GetBaryFaceFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, const std::vector<typename MeshType::FaceType*> &orderedFaces, typename MeshType::CoordType &bary, typename MeshType::FaceType* &chosen) { int index; bool found=GetBaryFaceFromUV(m,U,V,bary,index); if(!found) { chosen=0; return false; } chosen=orderedFaces[index]; return true; } template <class MeshType> bool GetCoordFromUV(const MeshType &m, const typename MeshType::ScalarType &U, const typename MeshType::ScalarType &V, typename MeshType::CoordType &val, bool rpos=false) { typedef typename MeshType::ScalarType ScalarType; const ScalarType _EPSILON = (ScalarType)0.00001; for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; vcg::Point2<ScalarType> tex0=vcg::Point2<ScalarType>(f->cV(0)->T().U(),f->cV(0)->T().V()); vcg::Point2<ScalarType> tex1=vcg::Point2<ScalarType>(f->cV(1)->T().U(),f->cV(1)->T().V()); vcg::Point2<ScalarType> tex2=vcg::Point2<ScalarType>(f->cV(2)->T().U(),f->cV(2)->T().V()); vcg::Point2<ScalarType> test=vcg::Point2<ScalarType>(U,V); vcg::Triangle2<ScalarType> t2d=vcg::Triangle2<ScalarType>(tex0,tex1,tex2); ScalarType area=(tex1-tex0)^(tex2-tex0); ///then find if the point 2d falls inside typename MeshType::CoordType bary; if ((area>_EPSILON)&&(t2d.InterpolationParameters(test,bary.X(),bary.Y(),bary.Z()))) { ///approximation errors for (int x=0;x<3;x++) { if (((bary[x])<=0)&&(bary[x]>=-_EPSILON)) bary[x]=0; else if (((bary[x])>=1)&&(bary[x]<=1+_EPSILON)) bary[x]=1; } ScalarType diff= (ScalarType)(1.0-bary.X()-bary.Y()-bary.Z()); bary.X()+=diff; if (!rpos) val=f->cP(0)*bary.X()+f->cP(1)*bary.Y()+f->cP(0)*bary.Z(); else val=f->cV(0)->RPos*bary.X()+f->cV(1)->RPos*bary.Y()+f->cV(2)->RPos*bary.Z(); return true; } } return false; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVEdgeSize(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=100.f; assert(m.fn>0); for (int i=0;i<m.face.size();i++) { ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=m.face[i].V(j)->T().P(); vcg::Point2<ScalarType> uv1=m.face[i].V((j+1)%3)->T().P(); ScalarType test=(uv0-uv1).Norm(); if (test<smallest) smallest=test; } } return smallest; } template <class MeshType> typename MeshType::ScalarType GetSmallestUVHeight(const MeshType &m) { typedef typename MeshType::ScalarType ScalarType; ScalarType smallest=(ScalarType)100.0; ScalarType eps=(ScalarType)0.0001; assert(m.fn>0); for (unsigned int i=0;i<m.face.size();i++) { const typename MeshType::FaceType *f=&m.face[i]; ///approximation errors for (int j=0;j<3;j++) { vcg::Point2<ScalarType> uv0=f->cV(j)->cT().P(); vcg::Point2<ScalarType> uv1=f->cV1(j)->cT().P(); vcg::Point2<ScalarType> uv2=f->cV2(j)->cT().P(); ScalarType area=fabs((uv1-uv0)^(uv2-uv0)); ScalarType base=(uv1-uv2).Norm(); ScalarType h_test=area/base; if (h_test<smallest) smallest=h_test; } } if (smallest<eps) smallest=(ScalarType)eps; if (smallest>(ScalarType)0.05) smallest=(ScalarType)0.05; return smallest; } template <class MeshType> void ParametrizeStarEquilateral(typename MeshType::VertexType *center, bool /*subvertices=true*/) { ///initialize domain typedef typename MeshType::VertexType VertexType; typedef typename MeshType::FaceType FaceType; typedef typename MeshType::CoordType CoordType; MeshType parametrized; std::vector<VertexType*> vertices,ordVert; std::vector<VertexType*> HresVert; std::vector<FaceType*> faces; vertices.push_back(center); getSharedFace<MeshType>(vertices,faces); CopyMeshFromFaces<MeshType>(faces,ordVert,parametrized); ///parametrize and then copy back ParametrizeStarEquilateral<MeshType>(parametrized); for (unsigned int i=0;i<ordVert.size();i++) ordVert[i]->T().P()=parametrized.vert[i].T().P(); ///initialize sub-vertices getHresVertex<FaceType>(faces,HresVert); for (unsigned int i=0;i<HresVert.size();i++) { FaceType *father=HresVert[i]->father; CoordType Bary=HresVert[i]->Bary; InterpolateUV<MeshType>(father,Bary,HresVert[i]->T().U(),HresVert[i]->T().V()); } } #endif
omp_parallel_firstprivate.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdlib.h> #include "omp_testsuite.h" //static int sum1 = 789; int test_omp_parallel_firstprivate() { int sum, num_threads,sum1; int known_sum; sum = 0; sum1=7; num_threads = 0; #pragma omp parallel firstprivate(sum1) { /*printf("sum1=%d\n",sum1);*/ int i; #pragma omp for for (i = 1; i < 1000; i++) { sum1 = sum1 + i; } /*end of for*/ #pragma omp critical { sum = sum + sum1; num_threads++; } /*end of critical*/ } /* end of parallel*/ known_sum = (999 * 1000) / 2 + 7 * num_threads; return (known_sum == sum); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_parallel_firstprivate()) { num_failed++; } } return num_failed; }
convolutiondepthwise_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 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 convdw3x3s1_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); const float bias0 = bias ? bias[g] : 0.f; const float* kernel0 = kernel + g * 9; float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(g); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i + 1 < outh; i += 2) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; float sum2 = bias0; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr = sum; *outptr2 = sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2_sse(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); const float bias0 = bias ? bias[g] : 0.f; const float* kernel0 = kernel + g * 9; float* outptr = out; const float* img0 = bottom_blob.channel(g); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
GB_subassign_06s.c
//------------------------------------------------------------------------------ // GB_subassign_06s: C(I,J)<M> = A ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // Method 06s: C(I,J)<M> = A ; using S // M: present // Mask_comp: false // C_replace: false // accum: NULL // A: matrix // S: constructed (see also Method 06n) #define GB_FREE_WORK GB_FREE_TWO_SLICE #include "GB_subassign_methods.h" GrB_Info GB_subassign_06s ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix M, const GrB_Matrix A, const GrB_Matrix S, GB_Context Context ) { //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_GET_C ; GB_GET_MASK ; const bool M_is_hyper = M->is_hyper ; const int64_t Mnvec = M->nvec ; GB_GET_A ; GB_GET_S ; GrB_BinaryOp accum = NULL ; //-------------------------------------------------------------------------- // Method 06s: C(I,J)<M> = A ; using S //-------------------------------------------------------------------------- // Time: O((nnz(A)+nnz(S))*log(m)) where m is the # of entries in a vector // of M, not including the time to construct S=C(I,J). If A, S, and M // are similar in sparsity, then this method can perform well. If M is // very sparse, Method 06n should be used instead. This method is selected // if nnz (A) < nnz (M). // Method 06s and 14 are very similar. //-------------------------------------------------------------------------- // Parallel: Z=A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20) //-------------------------------------------------------------------------- GB_SUBASSIGN_TWO_SLICE (A, S) ; //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (int taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_TASK_DESCRIPTOR_PHASE1 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get A(:,j) and S(:,j) //------------------------------------------------------------------ int64_t j = (Zh == NULL) ? k : Zh [k] ; GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ; GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ; //------------------------------------------------------------------ // get M(:,j) //------------------------------------------------------------------ int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; //------------------------------------------------------------------ // do a 2-way merge of S(:,j) and A(:,j) //------------------------------------------------------------------ // jC = J [j] ; or J is a colon expression // int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = Si [pS] ; int64_t iA = Ai [pA] ; if (iS < iA) { // S (i,j) is present but A (i,j) is not GB_MIJ_BINARY_SEARCH (iS) ; if (mij) { // ----[C . 1] or [X . 1]------------------------------- // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; } GB_NEXT (S) ; } else if (iA < iS) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH (iA) ; if (mij) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (A) ; } else { // both S (i,j) and A (i,j) present GB_MIJ_BINARY_SEARCH (iA) ; if (mij) { // ----[C A 1] or [X A 1]------------------------------- // [C A 1]: action: ( =A ): A to C no accum // [X A 1]: action: ( undelete ): zombie lives GB_C_S_LOOKUP ; GB_noaccum_C_A_1_matrix ; } GB_NEXT (S) ; GB_NEXT (A) ; } } // while list S (:,j) has entries. List A (:,j) exhausted while (pS < pS_end) { // S (i,j) is present but A (i,j) is not int64_t iS = Si [pS] ; GB_MIJ_BINARY_SEARCH (iS) ; if (mij) { // ----[C . 1] or [X . 1]----------------------------------- // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; } GB_NEXT (S) ; } // while list A (:,j) has entries. List S (:,j) exhausted while (pA < pA_end) { // S (i,j) is not present, A (i,j) is present int64_t iA = Ai [pA] ; GB_MIJ_BINARY_SEARCH (iA) ; if (mij) { // ----[. A 1]---------------------------------------------- // [. A 1]: action: ( insert ) task_pending++ ; } GB_NEXT (A) ; } } GB_PHASE1_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (int taskid = 0 ; taskid < ntasks ; taskid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- GB_GET_TASK_DESCRIPTOR_PHASE2 ; //---------------------------------------------------------------------- // compute all vectors in this task //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // get A(:,j) and S(:,j) //------------------------------------------------------------------ int64_t j = (Zh == NULL) ? k : Zh [k] ; GB_GET_MAPPED_VECTOR (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X) ; GB_GET_MAPPED_VECTOR (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S) ; //------------------------------------------------------------------ // get M(:,j) //------------------------------------------------------------------ int64_t pM_start, pM_end ; GB_VECTOR_LOOKUP (pM_start, pM_end, M, j) ; //------------------------------------------------------------------ // do a 2-way merge of S(:,j) and A(:,j) //------------------------------------------------------------------ // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = Si [pS] ; int64_t iA = Ai [pA] ; if (iS < iA) { // S (i,j) is present but A (i,j) is not GB_NEXT (S) ; } else if (iA < iS) { // S (i,j) is not present, A (i,j) is present GB_MIJ_BINARY_SEARCH (iA) ; if (mij) { // ----[. A 1]------------------------------------------ // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; } GB_NEXT (A) ; } else { // both S (i,j) and A (i,j) present GB_NEXT (S) ; GB_NEXT (A) ; } } // while list A (:,j) has entries. List S (:,j) exhausted while (pA < pA_end) { // S (i,j) is not present, A (i,j) is present int64_t iA = Ai [pA] ; GB_MIJ_BINARY_SEARCH (iA) ; if (mij) { // ----[. A 1]---------------------------------------------- // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; } GB_NEXT (A) ; } } GB_PHASE2_TASK_WRAPUP ; } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
faith.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <omp.h> #include "common.h" #define SATTHRESH (0.1f) #define VALTHRESH (0.05f) #define VALSUPTHRESH (0.87f) typedef struct { short hue; float saturation, value; } hsv_t; typedef struct { size_t w, h; hsv_t* pixels; } hsvimg_t; static short _partitionedHues[] = { 0, 90, 185, }; #define NUMPART (sizeof(_partitionedHues)/sizeof(_partitionedHues[0])) static struct { float max; size_t partition; } _partitions[] = { { 30.f, 0 }, { 90.f, 1 }, { 240.f, 2 }, { 999.f, 0 }, }; static short C1, C2, C3, C4; static inline int _underThresh(hsv_t p) { if(p.saturation < SATTHRESH) return 1; if(p.value < VALTHRESH) return 1; if(p.value > VALSUPTHRESH) return 1; return 0; } #define MAX(A, B, C) ((A >= B && A >= C) ? A : (B >= A && B >= C) ? B : C) #define MIN(A, B, C) ((A <= B && A <= C) ? A : (B <= A && B <= C) ? B : C) static inline hsv_t _toHSV(pixel_t ip) { hsv_t ret; float r = (float)ip.r / 255.f, g = (float)ip.g / 255.f, b = (float)ip.b / 255.f; float max = MAX(r, g, b); float min = MIN(r, g, b); ret.value = (max + min) / 2.f; if(max == min){ ret.hue = ret.saturation = 0.f; // achromatic }else{ float C = max - min; ret.saturation = C / (1.f - fabs(2.f * ret.value - 1.f)); if(max == r) { ret.hue = 60.f * fmodf((g - b) / C, 6.f); } else if(max == g) { ret.hue = 60.f * ((b - r) / C + 2.f); } else { ret.hue = 60.f * ((r - g) / C + 4.f); } } return ret; } static inline pixel_t _fromHSV(hsv_t p) { struct { float r, g, b; } ret; if(p.saturation == 0.f) { pixel_t ret = { p.value * 255.f, p.value * 255.f, p.value * 255.f }; return ret; } float C = (1.f - fabsf(2.f * p.value - 1.f)) * p.saturation; float X = C * (1.f - fabsf(fmodf(p.hue / 60.f, 2.f) - 1.f)); float m = 1.f * (p.value - 0.5f * C); if(p.hue < 0.f) { ret.r = ret.g = ret.b = m; } else if(p.hue < 60.f) { ret.r = C + m; ret.g = X + m; ret.b = m; } else if(p.hue < 120.f) { ret.r = X + m; ret.g = C + m; ret.b = m; } else if(p.hue < 180.f) { ret.r = m; ret.g = C + m; ret.b = X + m; } else if(p.hue < 240.f) { ret.r = m; ret.g = X + m; ret.b = C + m; } else if(p.hue < 300.f) { ret.r = X + m; ret.g = m; ret.b = C + m; } else if(p.hue < 360.f) { ret.r = C + m; ret.g = m; ret.b = X + m; } else { ret.r = ret.g = ret.b = m; } pixel_t realRet = { ret.r * 255.f, ret.g * 255.f, ret.b * 255.f }; return realRet; } typedef struct { size_t i; union { img_t asRGB; hsvimg_t asHSV; } in; union { img_t asRGB; hsvimg_t asHSV; } out; } tdata_t; static void _proc_toHSV(void* data) { tdata_t* mydata = (tdata_t*)data; size_t j; for(j = 0; j < mydata->in.asRGB.w; ++j) { A(mydata->out.asHSV, mydata->i, j) = _toHSV(A(mydata->in.asRGB, mydata->i, j)); } } static inline size_t PARTITION(float X) { size_t ii; for(ii = 0; ii < 6; ++ii) { if(X < _partitions[ii].max) { return _partitions[ii].partition; } } } static inline short dist(short p1, short p2) { if(p1 > p2) { short t = p1; p1 = p2; p2 = t; } short r1 = abs(p2 - p1); short r2 = abs(p1 + 360 - p2); return (r1 < r2) ? r1 : r2; } static inline void _incPartition(double* val, hsv_t p) { if(p.value < 0.5) { *val += sqrt((double)p.saturation * sin(p.value * 3.14159)); } else { double b = p.value; b = 4.0 * (b * b - 2.0 * b + 1.0); b *= b; *val += sqrt((double)p.saturation * b); } } static void _preprocRG(hsvimg_t img) { float min = 1.f, max = 0.f; float mins = 1.f, maxs = 0.f; size_t i, j; // get normalization extents for(i = 0; i < img.h; ++i) { for(j = 0; j < img.w; ++j) { if(A(img, i, j).value < min) min = A(img, i, j).value; if(A(img, i, j).value > max) max = A(img, i, j).value; if(A(img, i, j).saturation < mins) mins = A(img, i, j).saturation; if(A(img, i, j).saturation > maxs) maxs = A(img, i, j).saturation; } } // normalize and partition for(i = 0; i < img.h; ++i) { for(j = 0; j < img.w; ++j) { A(img, i, j).value = (A(img, i, j).value - min) / max; //A(img, i, j).saturation = (A(img, i, j).saturation - mins) / maxs; } } C1 = 0; C2 = 139; //C1 = 120; //C2 = 0; C3 = 240; C4 = 60; printf("color points: %d %d %d %d\n", C1, C2, C3, C4); } static void _preproc(hsvimg_t img) { float min = 1.f, max = 0.f; float mins = 1.f, maxs = 0.f; size_t i, j; double partitions[NUMPART]; size_t C1partition = 999; memset(partitions, 0, NUMPART * sizeof(double)); // get normalization extents for(i = 0; i < img.h; ++i) { for(j = 0; j < img.w; ++j) { if(A(img, i, j).value < min) min = A(img, i, j).value; if(A(img, i, j).value > max) max = A(img, i, j).value; if(A(img, i, j).saturation < mins) mins = A(img, i, j).saturation; if(A(img, i, j).saturation > maxs) maxs = A(img, i, j).saturation; } } // normalize and partition for(i = 0; i < img.h; ++i) { for(j = 0; j < img.w; ++j) { A(img, i, j).value = (A(img, i, j).value - min) / max; //A(img, i, j).saturation = (A(img, i, j).saturation - mins) / maxs; if(_underThresh(A(img, i, j))) continue; _incPartition(&partitions[PARTITION(A(img, i, j).hue)], A(img, i, j)); } } //printf("partitions: R:%.3f Y:%.3f G:%.3f b:%.3f B:%.3f\n", partitions[0], partitions[1], partitions[2], partitions[3], partitions[4]); printf("partitions: R:%.3f Y:%.3f G:%.3f b:%.3f\n", partitions[0], partitions[1], partitions[2], partitions[3]); // get dominant color double k =1e27f; for(i = 0; i < NUMPART; ++i) { if(partitions[i] < k) { k = partitions[i]; C1 = _partitionedHues[i]; C1partition = i; } } // get secondary color if(partitions[(C1partition + 1) % NUMPART] <= partitions[(C1partition + NUMPART - 1) % NUMPART]) { C2 = _partitionedHues[(C1partition + 1) % NUMPART]; } else { C2 = _partitionedHues[(C1partition + NUMPART - 1) % NUMPART]; } // determine 3rd and 4th points { short p1 = (C2 + C1) / 2; short p2 = (p1 + 180) % 360; if(dist(p1, C1) < dist(p2, C1)) { C3 = p2; C4 = p1; } else { C3 = p1; C4 = p2; } } printf("color points: %d %d %d %d\n", C1, C2, C3, C4); } static inline float _redistribVal(float p) { float s = sinf(p * 3.14159f / 2.f); #ifdef NOTSOBRIGHT float t = 0.05 + (0.65 * s + 0.15 * s * s); // add to 0.9 #else float t = 0.02 + (0.66 * s + 0.3 * sinf(s * 3.14159f / 2.f)); #endif return t; } static inline float applyMode(int mode, float t) { switch(mode) { case 0: return 0.5f * t + 0.5f * _redistribVal(t); case 1: return 0.5f * t + 0.5f * (1.f - _redistribVal(1.f - t)); default: return t; } } static inline float fixHue(float hue) { int mode = 0; float clor1 = C1, clor2 = C2; if(abs(clor2 - clor1) == dist(clor1, clor2)) { if(C2 > C1) { mode = 1; clor1 = C1; clor2 = C2; } else { mode = 0; clor1 = C2; clor2 = C1; } } else { if(C2 > C1) { clor1 = C2; clor2 = C1 + 360.f; mode = 0; } else { clor1 = C1; clor2 = C2 + 360.f; mode = 1; } } if(dist(hue, C4) < dist(hue, C3)) { float t = (float)dist(hue, clor1) / (float)(dist(hue, clor1) + dist(hue, clor2)); t = applyMode(mode, t); hue = clor1 + t * (float)dist(clor1, clor2); } else { hue = fmodf((hue + 180.f), 360); float t = (float)dist(hue, clor1) / (float)(dist(hue, clor1) + dist(hue, clor2)); t = 1.f - t; if(mode == 0) { t = _redistribVal(t); } else if(mode == 1) { t = 1.f - _redistribVal(1.f - t); } hue = clor1 + t * (float)dist(clor1, clor2); } return fmodf(hue, 360.f); } static void _proc_bulk(void* data) { tdata_t* mydata = (tdata_t*)data; size_t j; for(j = 0; j < mydata->in.asHSV.w; ++j) { hsv_t p = A(mydata->in.asHSV, mydata->i, j); short dC1 = dist(p.hue, C1), dC2 = dist(p.hue, C2), dC3 = dist(p.hue, C3), dC4 = dist(p.hue, C4); if(dC3 < dC4) { p.hue = fixHue(p.hue); // since it's outside of our color arc, desaturate it a bit float t = (1.f - _redistribVal(1.f - p.saturation)); p.saturation = t;//(0.3f * p.saturation + 0.7f * t); } else /*if(dC4 < dC3)*/ { p.hue = fixHue(p.hue); if(dC1 < dC2) { p.saturation = _redistribVal(p.saturation); } else { float t = _redistribVal(p.saturation); p.saturation = 0.4f * p.saturation + 0.6f * t; } } p.value = _redistribVal(p.value); p.value = 0.4f * p.value + 0.6f * _redistribVal(p.value); A(mydata->out.asRGB, mydata->i, j) = _fromHSV(p); } } static img_t _faithProc(img_t const img, void (*preproc)(hsvimg_t)) { img_t ret = { img.w, img.h, (pixel_t*)malloc(img.w * img.h * sizeof(pixel_t)) }; hsvimg_t hsvimg = { img.w, img.h, (hsv_t*)malloc(img.w * img.h * sizeof(hsvimg_t)) }; size_t i, j; tdata_t* datas; // process // toHSV datas = (tdata_t*)malloc(img.h * sizeof(tdata_t)); #pragma omp parallel for for(i = 0; i < img.h; ++i) { tdata_t* data = &datas[i]; data->i = i; data->in.asRGB = img; data->out.asHSV = hsvimg; _proc_toHSV(data); } // normalize preproc(hsvimg); // bulk processing #pragma omp parallel for for(i = 0; i < img.h; ++i) { tdata_t* data = &datas[i]; data->i = i; data->in.asHSV = hsvimg; data->out.asRGB = ret; _proc_bulk(data); } free(datas); free(hsvimg.pixels); return ret; } img_t faith(img_t const img) { return _faithProc(img, _preproc); } img_t rgfilter(img_t const img) { return _faithProc(img, _preprocRG); }
spmm.h
/*! * Copyright (c) 2020 by Contributors * \file array/cpu/spmm.h * \brief SPMM CPU kernel function header. */ #ifndef DGL_ARRAY_CPU_SPMM_H_ #define DGL_ARRAY_CPU_SPMM_H_ #include <dgl/array.h> #include <dgl/bcast.h> #include <algorithm> #include <limits> #include <memory> #include "spmm_binary_ops.h" #if !defined(_WIN32) #ifdef USE_AVX #include "intel/cpu_support.h" #ifdef USE_LIBXSMM #include "spmm_blocking_libxsmm.h" #endif // USE_LIBXSMM #endif // USE_AVX #endif // _WIN32 namespace dgl { namespace aten { namespace cpu { #if !defined(_WIN32) #ifdef USE_AVX /*! * \brief CPU kernel of SpMM on Csr format using Xbyak. * \param cpu_spec JIT'ed kernel * \param bcast Broadcast information. * \param csr The Csr matrix. * \param X The feature on source nodes. * \param W The feature on edges. * \param O The result feature on destination nodes. * \note it uses node parallel strategy, different threads are responsible * for the computation of different nodes. For each edge, it uses the * JIT'ed kernel. */ template <typename IdType, typename DType, typename Op> void SpMMSumCsrXbyak(dgl::ElemWiseAddUpdate<Op>* cpu_spec, const BcastOff& bcast, const CSRMatrix& csr, const DType* X, const DType* W, DType* O) { const bool has_idx = !IsNullArray(csr.data); const IdType* indptr = csr.indptr.Ptr<IdType>(); const IdType* indices = csr.indices.Ptr<IdType>(); const IdType* edges = csr.data.Ptr<IdType>(); int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; #pragma omp parallel for for (IdType rid = 0; rid < csr.num_rows; ++rid) { const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; DType* out_off = O + rid * dim; for (IdType j = row_start; j < row_end; ++j) { const IdType cid = indices[j]; const IdType eid = has_idx ? edges[j] : j; cpu_spec->run(out_off, X + cid * lhs_dim, W + eid * rhs_dim, dim); } } } #endif // USE_AVX #endif // _WIN32 /*! * \brief Naive CPU kernel of SpMM on Csr format. * \param cpu_spec JIT'ed kernel * \param bcast Broadcast information. * \param csr The Csr matrix. * \param X The feature on source nodes. * \param W The feature on edges. * \param O The result feature on destination nodes. * \note it uses node parallel strategy, different threads are responsible * for the computation of different nodes. */ template <typename IdType, typename DType, typename Op> void SpMMSumCsrNaive(const BcastOff& bcast, const CSRMatrix& csr, const DType* X, const DType* W, DType* O) { const bool has_idx = !IsNullArray(csr.data); const IdType* indptr = csr.indptr.Ptr<IdType>(); const IdType* indices = csr.indices.Ptr<IdType>(); const IdType* edges = csr.data.Ptr<IdType>(); int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; #pragma omp parallel for for (IdType rid = 0; rid < csr.num_rows; ++rid) { const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; DType* out_off = O + rid * dim; for (IdType j = row_start; j < row_end; ++j) { const IdType cid = indices[j]; const IdType eid = has_idx ? edges[j] : j; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs ? X + cid * lhs_dim + lhs_add : nullptr; const DType* rhs_off = Op::use_rhs ? W + eid * rhs_dim + rhs_add : nullptr; out_off[k] += Op::Call(lhs_off, rhs_off); } } } } /*! * \brief CPU kernel of SpMM on Csr format. * \param bcast Broadcast information. * \param csr The Csr matrix. * \param ufeat The feature on source nodes. * \param efeat The feature on edges. * \param out The result feature on destination nodes. * \note it uses node parallel strategy, different threads are responsible * for the computation of different nodes. */ template <typename IdType, typename DType, typename Op> void SpMMSumCsr(const BcastOff& bcast, const CSRMatrix& csr, NDArray ufeat, NDArray efeat, NDArray out) { const bool has_idx = !IsNullArray(csr.data); const IdType* indptr = csr.indptr.Ptr<IdType>(); const IdType* indices = csr.indices.Ptr<IdType>(); const IdType* edges = csr.data.Ptr<IdType>(); const DType* X = ufeat.Ptr<DType>(); const DType* W = efeat.Ptr<DType>(); int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; DType* O = out.Ptr<DType>(); CHECK_NOTNULL(indptr); CHECK_NOTNULL(O); if (Op::use_lhs) { CHECK_NOTNULL(indices); CHECK_NOTNULL(X); } if (Op::use_rhs) { if (has_idx) CHECK_NOTNULL(edges); CHECK_NOTNULL(W); } #if !defined(_WIN32) #ifdef USE_AVX #ifdef USE_LIBXSMM const bool no_libxsmm = bcast.use_bcast || std::is_same<DType, double>::value; if (!no_libxsmm) { SpMMSumCsrLibxsmm<IdType, DType, Op>(bcast, csr, ufeat, efeat, out); } else { #endif // USE_LIBXSMM typedef dgl::ElemWiseAddUpdate<Op> ElemWiseUpd; /* Prepare an assembler kernel */ static std::unique_ptr<ElemWiseUpd> asm_kernel_ptr( (dgl::IntelKernel<>::IsEnabled()) ? new ElemWiseUpd() : nullptr); /* Distribute the kernel among OMP threads */ ElemWiseUpd* cpu_spec = (asm_kernel_ptr && asm_kernel_ptr->applicable()) ? asm_kernel_ptr.get() : nullptr; if (cpu_spec && dim > 16 && !bcast.use_bcast) { SpMMSumCsrXbyak<IdType, DType, Op>(cpu_spec, bcast, csr, X, W, O); } else { #endif // USE_AVX #endif // _WIN32 SpMMSumCsrNaive<IdType, DType, Op>(bcast, csr, X, W, O); #if !defined(_WIN32) #ifdef USE_AVX } #ifdef USE_LIBXSMM } #endif // USE_LIBXSMM #endif // USE_AVX #endif // _WIN32 } /*! * \brief CPU kernel of SpMM on Coo format. * \param bcast Broadcast information. * \param coo The Coo matrix. * \param ufeat The feature on source nodes. * \param efeat The feature on edges. * \param out The result feature on destination nodes. * \note it uses node parallel strategy, different threads are responsible * for the computation of different nodes. To avoid possible data hazard, * we use atomic operators in the reduction phase. */ template <typename IdType, typename DType, typename Op> void SpMMSumCoo(const BcastOff& bcast, const COOMatrix& coo, NDArray ufeat, NDArray efeat, NDArray out) { const bool has_idx = !IsNullArray(coo.data); const IdType* row = coo.row.Ptr<IdType>(); const IdType* col = coo.col.Ptr<IdType>(); const IdType* edges = coo.data.Ptr<IdType>(); const DType* X = ufeat.Ptr<DType>(); const DType* W = efeat.Ptr<DType>(); int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; DType* O = out.Ptr<DType>(); const int64_t nnz = coo.row->shape[0]; // fill zero elements memset(O, 0, out.GetSize()); // spmm #pragma omp parallel for for (IdType i = 0; i < nnz; ++i) { const IdType rid = row[i]; const IdType cid = col[i]; const IdType eid = has_idx ? edges[i] : i; DType* out_off = O + cid * dim; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs ? X + rid * lhs_dim + lhs_add : nullptr; const DType* rhs_off = Op::use_rhs ? W + eid * rhs_dim + rhs_add : nullptr; const DType val = Op::Call(lhs_off, rhs_off); if (val != 0) { #pragma omp atomic out_off[k] += val; } } } } /*! * \brief CPU kernel of SpMM-Min/Max on Csr format. * \param bcast Broadcast information. * \param csr The Csr matrix. * \param ufeat The feature on source nodes. * \param efeat The feature on edges. * \param out The result feature on destination nodes. * \param argu Arg-Min/Max on source nodes, which refers the source node indices * correspond to the minimum/maximum values of reduction result on * destination nodes. It's useful in computing gradients of Min/Max * reducer. \param arge Arg-Min/Max on edges. which refers the source node * indices correspond to the minimum/maximum values of reduction result on * destination nodes. It's useful in computing gradients of Min/Max * reducer. \note It uses node parallel strategy, different threads are * responsible for the computation of different nodes. \note The result will * contain infinity for zero-degree nodes. */ template <typename IdType, typename DType, typename Op, typename Cmp> void SpMMCmpCsr(const BcastOff& bcast, const CSRMatrix& csr, NDArray ufeat, NDArray efeat, NDArray out, NDArray argu, NDArray arge) { const bool has_idx = !IsNullArray(csr.data); const IdType* indptr = static_cast<IdType*>(csr.indptr->data); const IdType* indices = static_cast<IdType*>(csr.indices->data); const IdType* edges = has_idx ? static_cast<IdType*>(csr.data->data) : nullptr; const DType* X = Op::use_lhs ? static_cast<DType*>(ufeat->data) : nullptr; const DType* W = Op::use_rhs ? static_cast<DType*>(efeat->data) : nullptr; const int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; DType* O = static_cast<DType*>(out->data); IdType* argX = Op::use_lhs ? static_cast<IdType*>(argu->data) : nullptr; IdType* argW = Op::use_rhs ? static_cast<IdType*>(arge->data) : nullptr; CHECK_NOTNULL(indptr); CHECK_NOTNULL(O); if (Op::use_lhs) { CHECK_NOTNULL(indices); CHECK_NOTNULL(X); CHECK_NOTNULL(argX); } if (Op::use_rhs) { if (has_idx) CHECK_NOTNULL(edges); CHECK_NOTNULL(W); CHECK_NOTNULL(argW); } #if !defined(_WIN32) #ifdef USE_AVX #ifdef USE_LIBXSMM const bool no_libxsmm = bcast.use_bcast || std::is_same<DType, double>::value; if (!no_libxsmm) { SpMMCmpCsrLibxsmm<IdType, DType, Op, Cmp>(bcast, csr, ufeat, efeat, out, argu, arge); } else { #endif // USE_LIBXSMM #endif // USE_AVX #endif // _WIN32 #pragma omp parallel for for (IdType rid = 0; rid < csr.num_rows; ++rid) { const IdType row_start = indptr[rid], row_end = indptr[rid + 1]; DType* out_off = O + rid * dim; IdType* argx_off = argX + rid * dim; IdType* argw_off = argW + rid * dim; for (IdType j = row_start; j < row_end; ++j) { const IdType cid = indices[j]; const IdType eid = has_idx ? edges[j] : j; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs ? X + cid * lhs_dim + lhs_add : nullptr; const DType* rhs_off = Op::use_rhs ? W + eid * rhs_dim + rhs_add : nullptr; const DType val = Op::Call(lhs_off, rhs_off); if (Cmp::Call(out_off[k], val)) { out_off[k] = val; if (Op::use_lhs) argx_off[k] = cid; if (Op::use_rhs) argw_off[k] = eid; } } } } #if !defined(_WIN32) #ifdef USE_AVX #ifdef USE_LIBXSMM } #endif // USE_LIBXSMM #endif // USE_AVX #endif // _WIN32 } /*! * \brief CPU kernel of SpMM-Min/Max on Coo format. * \param bcast Broadcast information. * \param coo The Coo matrix. * \param ufeat The feature on source nodes. * \param efeat The feature on edges. * \param out The result feature on destination nodes. * \param argu Arg-Min/Max on source nodes, which refers the source node indices * correspond to the minimum/maximum values of reduction result on * destination nodes. It's useful in computing gradients of Min/Max * reducer. \param arge Arg-Min/Max on edges. which refers the source node * indices correspond to the minimum/maximum values of reduction result on * destination nodes. It's useful in computing gradients of Min/Max * reducer. \note it uses node parallel strategy, different threads are * responsible for the computation of different nodes. To avoid possible data * hazard, we use atomic operators in the reduction phase. \note The result will * contain infinity for zero-degree nodes. */ template <typename IdType, typename DType, typename Op, typename Cmp> void SpMMCmpCoo(const BcastOff& bcast, const COOMatrix& coo, NDArray ufeat, NDArray efeat, NDArray out, NDArray argu, NDArray arge) { const bool has_idx = !IsNullArray(coo.data); const IdType* row = static_cast<IdType*>(coo.row->data); const IdType* col = static_cast<IdType*>(coo.col->data); const IdType* edges = has_idx ? static_cast<IdType*>(coo.data->data) : nullptr; const DType* X = Op::use_lhs ? static_cast<DType*>(ufeat->data) : nullptr; const DType* W = Op::use_rhs ? static_cast<DType*>(efeat->data) : nullptr; const int64_t dim = bcast.out_len, lhs_dim = bcast.lhs_len, rhs_dim = bcast.rhs_len; DType* O = static_cast<DType*>(out->data); IdType* argX = Op::use_lhs ? static_cast<IdType*>(argu->data) : nullptr; IdType* argW = Op::use_rhs ? static_cast<IdType*>(arge->data) : nullptr; const int64_t nnz = coo.row->shape[0]; // fill zero elements std::fill(O, O + out.NumElements(), Cmp::zero); // spmm #pragma omp parallel for for (IdType i = 0; i < nnz; ++i) { const IdType rid = row[i]; const IdType cid = col[i]; const IdType eid = has_idx ? edges[i] : i; DType* out_off = O + cid * dim; IdType* argx_off = Op::use_lhs ? argX + cid * dim : nullptr; IdType* argw_off = Op::use_rhs ? argW + cid * dim : nullptr; for (int64_t k = 0; k < dim; ++k) { const int64_t lhs_add = bcast.use_bcast ? bcast.lhs_offset[k] : k; const int64_t rhs_add = bcast.use_bcast ? bcast.rhs_offset[k] : k; const DType* lhs_off = Op::use_lhs ? X + rid * lhs_dim + lhs_add : nullptr; const DType* rhs_off = Op::use_rhs ? W + eid * rhs_dim + rhs_add : nullptr; const DType val = Op::Call(lhs_off, rhs_off); #pragma omp critical if (Cmp::Call(out_off[k], val)) { out_off[k] = val; if (Op::use_lhs) argx_off[k] = rid; if (Op::use_rhs) argw_off[k] = eid; } } } } } // namespace cpu } // namespace aten } // namespace dgl #endif // DGL_ARRAY_CPU_SPMM_H_
piCalc.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #define MARGIN 1e-12 void Usage(char* prog_name); int workshare(long long points); int sequential(long long points); int glob_sum_seq; int glob_sum_par; int main(){ printf("\n\n1000000 points\n"); printf("\nSEQUENTIAL\n"); sequential(1000000); printf("\nPARALLEL\n"); workshare(1000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n10000000 points\n"); printf("\nSEQUENTIAL\n"); sequential(10000000); printf("\nPARALLEL\n"); workshare(10000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n100000000 points\n"); printf("\nSEQUENTIAL\n"); sequential(100000000); printf("\nPARALLEL\n"); workshare(100000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n1000000000 points\n"); printf("\nSEQUENTIAL\n"); sequential(1000000000); printf("\nPARALLEL\n"); workshare(1000000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n10000000000 points\n"); printf("\nSEQUENTIAL\n"); sequential(10000000000); printf("\nPARALLEL\n"); workshare(10000000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); } int sequential(long long points) { long long n, i; double factor; double sum = 0.0; n = points; double timeStart = omp_get_wtime(); printf("Before for loop, factor = %f.\n", factor); for (i = 0; i < n; i++) { factor = (i % 2 == 0) ? 1.0 : -1.0; sum += factor/(2*i+1); } printf("After for loop, factor = %f.\n", factor); sum = 4.0*sum; printf("With n = %lld terms\n", n); printf(" Our estimate of pi = %.14f\n", sum); printf(" Ref estimate of pi = %.14f\n", 4.0*atan(1.0)); double timeStop = omp_get_wtime(); printf("Elapsed time: %f ", timeStop - timeStart); return 0; } int workshare(long long points) { long long n, i; double factor; double sum = 0.0; n = points; double timeStart = omp_get_wtime(); printf("Before for loop, factor = %f.\n", factor); #pragma omp parallel for \ private(i, factor) \ shared(n)\ reduction(+:sum) for (i = 0; i < n; i++) { factor = (i % 2 == 0) ? 1.0 : -1.0; sum += factor/(2*i+1); } printf("After for loop, factor = %f.\n", factor); sum = 4.0*sum; printf("With n = %lld terms\n", n); printf(" Our estimate of pi = %.14f\n", sum); printf(" Ref estimate of pi = %.14f\n", 4.0*atan(1.0)); double timeStop = omp_get_wtime(); printf("Elapsed time: %f ", timeStop - timeStart); return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <thread_count> <n>\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\n"); exit(0); }
DataVectorAlt.h
/***************************************************************************** * * Copyright (c) 2003-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014 by Centre for Geoscience Computing (GeoComp) * *****************************************************************************/ #ifndef __ESCRIPT_DATAVECTORALT_H__ #define __ESCRIPT_DATAVECTORALT_H__ #include "DataTypes.h" #include "system_dep.h" #include "Assert.h" #include "DataException.h" #include "WrappedArray.h" #include <sstream> namespace escript { namespace DataTypes { template <class T> class ESCRIPT_DLL_API DataVectorAlt { public: // // The type of the elements stored in the vector. typedef T ElementType; // // Various types exported to clients of this class. typedef const ElementType * const_pointer; typedef ElementType value_type; typedef DataTypes::vec_size_type size_type; typedef ElementType & reference; typedef const ElementType & const_reference; /** \brief Default constructor for DataVectorAlt. Description: Constructs an empty DataVectorAlt object. */ DataVectorAlt(); /** \brief Copy constructor for DataVectorAlt. Description: Constructs a DataVectorAlt object which is a copy of the given DataVectorAlt object. */ DataVectorAlt(const DataVectorAlt<T>& other); /** \brief Constructor for DataVectorAlt. Description: Constructs a DataVectorAlt object of length "size" with all elements initilised to "val". \param size - Input - Number of elements in the vector. \param val - Input - Initial value for all elements in the vector. Default is 0.0. \param blockSize - Input - size of blocks within the vector, overall vector size must be a precise multiple of the block size. Default is 1. In escript::Data, blocksize corresponds to the number of elements required to hold all the data-points for a sample, ie: the product of the dimensions of a data-point and the number of data-points per sample. Size is the total number of elements required to hold all elements for all data-points in the given object, ie: number of samples * blocksize. */ DataVectorAlt(const size_type size, const value_type val=0.0, const size_type blockSize=1); /** \brief Default destructor for DataVectorAlt. Description: Destroys the current DataVectorAlt object. */ ~DataVectorAlt(); /** \brief Resize the DataVectorAlt to the given length "newSize". All current data is lost. All elements in the new DataVectorAlt are initialised to "newVal". \param newSize - Input - New size for the vector. \param newVal - Input - New initial value for all elements in the vector. \param newBlockSize - Input - New block size for the vector. */ void resize(const size_type newSize, const value_type newVal=0.0, const size_type newBlockSize=1); /** \brief Populates the vector with the data from value. This method currently throws an exception if the specified number of copies won't fit. \warning This function does not attempt to perform shape checking. */ void copyFromArray(const WrappedArray& value, size_type copies); // Please make sure that any implementation changes here are reflected in the specialised // version in the .cpp file void copyFromArrayToOffset(const WrappedArray& value, size_type offset, size_type copies); /** \brief Return the number of elements in this DataVectorAlt. */ inline size_type size() const; /** \brief DataVectorAlt assignment operator "=". Assign the given DataVectorAlt object to this. */ DataVectorAlt& operator=(const DataVectorAlt<T>& other); /** \brief DataVectorAlt equality comparison operator "==". Return true if the given DataVectorAlt is equal to this. */ bool operator==(const DataVectorAlt<T>& other) const; /** \brief DataVectorAlt inequality comparison operator "!=". Return true if the given DataVectorAlt is not equal to this. */ bool operator!=(const DataVectorAlt<T>& other) const; /** \brief Return a reference to the element at position i in this DataVectorAlt. Will throw an exception if an invalid index "i" is given. NB: access to the element one past the end of the vector is permitted in order to provide a facility equivalent to an end() pointer. */ inline reference operator[](const size_type i); inline const_reference operator[](const size_type i) const; // for compatibility with std::vector ElementType* data(); const ElementType* data() const; protected: private: size_type m_size; size_type m_dim; size_type m_N; ElementType* m_array_data; }; template <class T> inline typename DataVectorAlt<T>::ElementType* DataVectorAlt<T>::data() { return m_array_data; } template <class T> inline const typename DataVectorAlt<T>::ElementType* DataVectorAlt<T>::data() const { return m_array_data; } template <class T> inline typename DataVectorAlt<T>::size_type DataVectorAlt<T>::size() const { return m_size; } template <class T> inline typename DataVectorAlt<T>::reference DataVectorAlt<T>::operator[](const DataVectorAlt::size_type i) { ESYS_ASSERT(i<size(), "DataVectorAlt: invalid index specified, " << i << " of " << size()); return m_array_data[i]; } template <class T> inline typename DataVectorAlt<T>::const_reference DataVectorAlt<T>::operator[](const DataVectorAlt::size_type i) const { ESYS_ASSERT(i<size(), "DataVectorAlt: invalid index specified. " << i << " of " << size()); return m_array_data[i]; } template <class T> DataTypes::DataVectorAlt<T>::DataVectorAlt() : m_size(0), m_dim(0), m_N(0), m_array_data(0) { } template <class T> DataTypes::DataVectorAlt<T>::DataVectorAlt(const DataVectorAlt& other) : m_size(other.m_size), m_dim(other.m_dim), m_N(other.m_N), m_array_data(0) { m_array_data=reinterpret_cast<T*>(malloc(sizeof(T)*m_size)); int i; #pragma omp parallel for private(i) schedule(static) for (i=0; i<m_size; i++) { m_array_data[i] = other.m_array_data[i]; } } template <class T> DataTypes::DataVectorAlt<T>::DataVectorAlt(const DataVectorAlt<T>::size_type size, const DataVectorAlt<T>::value_type val, const DataVectorAlt<T>::size_type blockSize) : m_size(size), m_dim(blockSize), m_array_data(0) { resize(size, val, blockSize); } template <class T> DataTypes::DataVectorAlt<T>::~DataVectorAlt() { // clear data members m_size = -1; m_dim = -1; m_N = -1; if (m_array_data!=0) { free(m_array_data); } m_array_data=0; } template <class T> void DataVectorAlt<T>::resize(const DataVectorAlt<T>::size_type newSize, const DataVectorAlt<T>::value_type newValue, const DataVectorAlt<T>::size_type newBlockSize) { // The < 1 is to catch both ==0 and negatives if ( newBlockSize < 1) { std::ostringstream oss; oss << "DataVectorAlt: invalid blockSize specified (" << newBlockSize << ')'; throw DataException(oss.str()); } if ( newSize < 0 ) { std::ostringstream oss; oss << "DataVectorAlt: invalid new size specified (" << newSize << ')'; throw DataException(oss.str()); } if ( (newSize % newBlockSize) != 0) { std::ostringstream oss; oss << "DataVectorAlt: newSize is not a multiple of blockSize: (" << newSize << ", " << newBlockSize<< ')'; throw DataException(oss.str()); } m_size = newSize; m_dim = newBlockSize; m_N = newSize / newBlockSize; if (m_array_data!=0) { free(m_array_data); } m_array_data=reinterpret_cast<T*>(malloc(sizeof(T)*m_size)); int i; #pragma omp parallel for private(i) schedule(static) for (i=0; i<m_size; i++) { m_array_data[i] = newValue; } } template <class T> DataVectorAlt<T>& DataVectorAlt<T>::operator=(const DataVectorAlt& other) { assert(m_size >= 0); m_size = other.m_size; m_dim = other.m_dim; m_N = other.m_N; if (m_array_data!=0) { free(m_array_data); } m_array_data=reinterpret_cast<T*>(malloc(sizeof(T)*m_size)); int i; #pragma omp parallel for private(i) schedule(static) for (i=0; i<m_size; i++) { m_array_data[i] = other.m_array_data[i]; } return *this; } template <class T> bool DataVectorAlt<T>::operator==(const DataVectorAlt& other) const { assert(m_size >= 0); if (m_size!=other.m_size) { return false; } if (m_dim!=other.m_dim) { return false; } if (m_N!=other.m_N) { return false; } for (int i=0; i<m_size; i++) { if (m_array_data[i] != other.m_array_data[i]) { return false; } } return true; } template <class T> bool DataVectorAlt<T>::operator!=(const DataVectorAlt& other) const { return !(*this==other); } template <class T> void DataVectorAlt<T>::copyFromArrayToOffset(const WrappedArray& value, size_type offset, size_type copies) { const DataTypes::ShapeType& tempShape=value.getShape(); size_type len=DataTypes::noValues(tempShape); if (offset+len*copies>size()) { std::ostringstream ss; ss << "Error - not enough room for that DataPoint at that offset. ("; ss << "offset=" << offset << " + " << " len=" << len << " >= " << size(); throw DataException(ss.str()); } size_type si=0,sj=0,sk=0,sl=0; switch (value.getRank()) { case 0: for (size_type z=0;z<copies;++z) { m_array_data[offset+z]=value.getElt(); } break; case 1: for (size_type z=0;z<copies;++z) { for (size_t i=0;i<tempShape[0];++i) { m_array_data[offset+i]=value.getElt(i); } offset+=len; } break; case 2: si=tempShape[0]; sj=tempShape[1]; for (size_type z=0;z<copies;++z) { for (size_type i=0;i<si;i++) { for (size_type j=0;j<sj;j++) { m_array_data[offset+DataTypes::getRelIndex(tempShape,i,j)]=value.getElt(i,j); } } offset+=len; } break; case 3: si=tempShape[0]; sj=tempShape[1]; sk=tempShape[2]; for (size_type z=0;z<copies;++z) { for (size_type i=0;i<si;i++) { for (size_type j=0;j<sj;j++) { for (size_type k=0;k<sk;k++) { m_array_data[offset+DataTypes::getRelIndex(tempShape,i,j,k)]=value.getElt(i,j,k); } } } offset+=len; } break; case 4: si=tempShape[0]; sj=tempShape[1]; sk=tempShape[2]; sl=tempShape[3]; for (size_type z=0;z<copies;++z) { for (size_type i=0;i<si;i++) { for (size_type j=0;j<sj;j++) { for (size_type k=0;k<sk;k++) { for (size_type l=0;l<sl;l++) { m_array_data[offset+DataTypes::getRelIndex(tempShape,i,j,k,l)]=value.getElt(i,j,k,l); } } } } offset+=len; } break; default: std::ostringstream oss; oss << "Error - unknown rank. Rank=" << value.getRank(); throw DataException(oss.str()); } } template <class T> void DataVectorAlt<T>::copyFromArray(const WrappedArray& value, size_type copies) { DataTypes::ShapeType tempShape=value.getShape(); DataVectorAlt<T>::size_type nelements=DataTypes::noValues(tempShape)*copies; if (m_array_data!=0) { free(m_array_data); } m_array_data=reinterpret_cast<T*>(malloc(sizeof(T)*nelements)); m_size=nelements; // total amount of elements m_dim=m_size; // elements per sample m_N=1; // number of samples copyFromArrayToOffset(value,0,copies); } } // end of namespace } // end of namespace #endif // __ESCRIPT_DATAVECTORALT_H__
GB_unop__identity_uint64_int64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #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_uint64_int64 // op(A') function: GB_unop_tran__identity_uint64_int64 // C type: uint64_t // A type: int64_t // cast: uint64_t cij = (uint64_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = (uint64_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = (uint64_t) aij ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint64_int64 ( uint64_t *Cx, // Cx and Ax may be aliased const int64_t *Ax, const int8_t *GB_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) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (int64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; uint64_t z = (uint64_t) aij ; Cx [p] = z ; } #endif } 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 ; int64_t aij = Ax [p] ; uint64_t z = (uint64_t) aij ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__identity_uint64_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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
Par-08-ParallelForParallelFor.c
int main(int argc, char **argv) { int a[4] = {1,2,3,4}; int b[4] = {0, 0, 0, 0}; #pragma omp parallel { #pragma omp for for (int i = 0; i < 4; ++i) { a[i] = 3*a[i]; } } #pragma omp parallel for for (int j = 0; j < 4; ++j) { b[j] = b[j] + a[j]; } 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] = 8; tile_size[3] = 512; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } 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-3,4)),ceild(4*t2-Nz-4,8));t3<=min(min(min(floord(4*t2+Ny,8),floord(Nt+Ny-4,8)),floord(2*t1+Ny+1,8)),floord(4*t1-4*t2+Nz+Ny-1,8));t3++) { for (t4=max(max(max(0,ceild(t1-255,256)),ceild(4*t2-Nz-508,512)),ceild(8*t3-Ny-508,512));t4<=min(min(min(min(floord(4*t2+Nx,512),floord(Nt+Nx-4,512)),floord(2*t1+Nx+1,512)),floord(8*t3+Nx+4,512)),floord(4*t1-4*t2+Nz+Nx-1,512));t4++) { for (t5=max(max(max(max(max(0,2*t1),4*t1-4*t2+1),4*t2-Nz+2),8*t3-Ny+2),512*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,2*t1+3),4*t2+2),8*t3+6),512*t4+510),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(8*t3,t5+1);t7<=min(8*t3+7,t5+Ny-2);t7++) { lbv=max(512*t4,t5+1); ubv=min(512*t4+511,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; }
matc.c
/***************************************************************************** * * Elmer, A Finite Element Software for Multiphysical Problems * * Copyright 1st April 1995 - , CSC - IT Center for Science Ltd., Finland * * This 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library (in file ../LGPL-2.1); if not, write * to the Free Software Foundation, Inc., 51 Franklin Street, * Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ /******************************************************************************* * * MATC main module. * ******************************************************************************* * * Author: Juha Ruokolainen * * Address: CSC - IT Center for Science Ltd. * Keilaranta 14, P.O. BOX 405 * 02101 Espoo, Finland * Tel. +358 0 457 2723 * Telefax: +358 0 457 2302 * EMail: Juha.Ruokolainen@csc.fi * * Date: 30 May 1996 * * Modified by: * * Date of modification: * ******************************************************************************/ /*********************************************************************** | | MATC - Last Edited 9. 8. 1988 | ***********************************************************************/ /*====================================================================== |Syntax of the manual pages: | |FUNCTION NAME(...) params ... | $ usage of the function and type of the parameters ? explane the effects of the function = return value and the type of value if not of type int @ globals effected directly by this routine ! current known bugs or limitations & functions called by this function ~ these functions may interest you as an alternative function or | because they control this function somehow ^=====================================================================*/ /* * $Id: matc.c,v 1.7 2007/06/08 08:12:17 jpr Exp $ * * $Log: matc.c,v $ * Revision 1.7 2007/06/08 08:12:17 jpr * *** empty log message *** * * Revision 1.6 2006/02/07 10:21:42 jpr * Changed visibility of some variables to local scope. * * Revision 1.5 2006/02/02 06:54:44 jpr * small formatting changes. * * Revision 1.3 2005/08/25 13:44:22 vierinen * windoze stuff * * Revision 1.2 2005/05/27 12:26:20 vierinen * changed header install location * * Revision 1.1.1.1 2005/04/14 13:29:14 vierinen * initial matc automake package * * Revision 1.2 1998/08/01 12:34:48 jpr * * Added Id, started Log. * * */ #define MODULE_MATC #include "elmer/matc.h" #include "str.h" #include "../config.h" #ifdef DEBUG static FILE *fplog; static int tot; #pragma omp threadprivate (fplog, tot) #endif /*====================================================================== ? main program, initialize few constants and go for it. ^=====================================================================*/ void mtc_init( FILE *input_file, FILE *output_file, FILE *error_file ) { VARIABLE *ptr; char str[256]; int i; /* i'm getting tired with all these i's */ static char *evalHelp = { "eval( str )\n\n" "Evaluate content variable. Another form of this command is @str.\n" }; static char *sourceHelp = { "source( name )\n\n" "Execute commands from file given name.\n" }; static char *helpHelp = { "help or help(\"symbol\")\n\n" "First form of the command gives list of available commands.\n" "Second form gives help on specific routine.\n" }; #ifdef _OPENMP /* Allocate listheaders for each thread separately */ #pragma omp parallel { /* Do malloc and initialize listheaders */ listheaders = (LIST *) malloc(sizeof(LIST)*MAX_HEADERS); /* memory allocations */ listheaders[ALLOCATIONS].next = NULL; listheaders[ALLOCATIONS].name = "Allocations"; /* global CONSTANTS */ listheaders[CONSTANTS].next = NULL; listheaders[CONSTANTS].name = "Constants"; /* global VARIABLES */ listheaders[VARIABLES].next = NULL; listheaders[VARIABLES].name = "Currently defined VARIABLES"; /* internal commands */ listheaders[COMMANDS].next = NULL; listheaders[COMMANDS].name = "Builtin Functions"; /* user defined functions */ listheaders[FUNCTIONS].next = NULL; listheaders[FUNCTIONS].name = "User Functions"; } #endif /* _OPENMP */ #ifdef DEBUG fplog = fopen("matcdbg","w"); #endif ALLOC_HEAD = (LIST *)NULL; /* * input & output & error streams */ math_in = input_file; math_err = error_file; math_out = output_file; mtr_com_init(); /* initialize matrix handling commands */ var_com_init(); /* "" VARIABLE "" "" */ fnc_com_init(); /* "" function handling commands */ fil_com_init(); /* "" file handling commands */ gra_com_init(); /* "" graphics commands */ str_com_init(); /* "" string handling */ /* * and few others. */ com_init( "eval" , FALSE, FALSE, com_apply, 1, 1, evalHelp ); com_init( "source" , FALSE, FALSE, com_source, 1, 1, sourceHelp ); com_init( "help" , FALSE, FALSE, com_help , 0, 1, helpHelp ); com_init( "quit" , FALSE, FALSE, com_quit , 0, 0, "quit\n" ); com_init( "exit" , FALSE, FALSE, com_quit , 0, 0, "exit\n" ); /* * these constants will always be there for you. */ ptr = const_new("true", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 1.0; ptr = const_new("false", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 0.0; ptr = const_new("stdin", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 0; ptr = const_new("stdout", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 1; ptr = const_new("stderr", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 2; ptr = const_new("pi", TYPE_DOUBLE, 1, 1); M(ptr,0,0) = 2*acos(0.0); #if 0 /* * trap INTERRUPT and Floating Point Exeption signals */ signal(SIGFPE, sig_trap); sprintf( str, "%s/lib/mc.ini", getenv("ELMER_POST_HOME") ); if ( (math_in = fopen( str, "r" ) ) != (FILE *)NULL) { doread(); fclose( math_in ); } /* * and finally standard input. */ math_in = stdin; doread(); var_free(); com_free(); fnc_free(); const_free(); mem_free_all(); #ifdef DEBUG fclose(fplog); #endif #endif return; /* done */ } char * mtc_domath( char *str ) { VARIABLE *headsave; /* this should not be here */ jmp_buf jmp, *savejmp; /* save program context */ void (*sigfunc)() = (void (*)())signal( SIGINT, sig_trap ); if ( !str || !*str ) { str = (char *)doread(); signal( SIGINT, sigfunc ); return math_out_str; } savejmp = jmpbuf; jmpbuf = &jmp; #ifdef DEBUG fprintf( stderr, "got [%s]\n", str ); #endif if ( math_out_str ) math_out_str[0] = '\0'; math_out_count = 0; /* * try it */ if (*str != '\0') { ALLOC_HEAD = (LIST *)NULL; headsave = (VARIABLE *)VAR_HEAD; /* * normal return takes branch 1, * error() takes branch 2, * quit() takes branch 3. */ switch (setjmp(*jmpbuf)) { case 0: (void)doit( str ); longjmp(*jmpbuf, 1); break; case 1: break; case 2: VAR_HEAD = (LIST *)headsave; break; case 3: break; } } jmpbuf = savejmp; signal( SIGINT, sigfunc ); return math_out_str; } char *doread() /*====================================================================== ? doread() is really the main loop of this program. Function reads | it's input as strings and gives them to function doit() for | execution. setjmp() function is used for error recovery. | | Memory allocated during the lifetime of this function is | collected to a list represented by the global VARIABLE | ALLOCLIST *alloc_list. If function error() is called, this | list is used to deallocte memory. Normally (well I certainly | hope so) functions which allocate memory deallocate it themselves. | | Program stays in this function until an end of file -condition | is reached or exit- or quit-commands are given. | @ jmp_buf *jmpbuf, ALLOC_LIST *alloc_list & ALLOCMEM, FREEMEM, setjmp(), longjmp() ~ doit(), quit(), error() ^=====================================================================*/ { VARIABLE *headsave; /* this should not be here */ jmp_buf jmp, *savejmp; /* save program context */ char *p, *q; /* buffer for input stream */ savejmp = jmpbuf; jmpbuf = &jmp; if ( math_out_str ) math_out_str[0] = '\0'; math_out_count = 0; p = q = ALLOCMEM(4096); /* * try it */ while(dogets(p, PMODE_MAIN)) { if (*p != '\0') { ALLOC_HEAD = (LIST *)NULL; headsave = (VARIABLE *)VAR_HEAD; /* * normal return takes branch 1, * error() takes branch 2, * quit() takes branch 3. */ switch (setjmp(*jmpbuf)) { case 0: (void)doit(p); longjmp(*jmpbuf, 1); break; case 1: break; case 2: VAR_HEAD = (LIST *)headsave; break; case 3: goto ret; break; } } } ret: jmpbuf = savejmp; FREEMEM(q); return math_out_str; } VARIABLE *com_quit() /*====================================================================== ? Quit current doread entry by longjumping back to it (nasty). & longjmp ~ doread ^=====================================================================*/ { longjmp(*jmpbuf, 3); return (VARIABLE *)NULL; /* won't be executed (hopefully) */ } int dogets(buff, prompt) char *buff; char *prompt; /*====================================================================== ? Get line from input stream. If both input & output streams are | connected to terminal, this function gives user one of three | (default) prompts: | | MATC> | - normal prompt (PMODE_MAIN) | ....> | - begin end- block is beign defined (PMODE_BLOCK) | ####> (PMODE_CONT) | - user has given a #-sign as a last character of | previous line, this line will be catenated with it | | If current comment character is found from input stream, the | line after this character is discarded. Likewise if current | system command character is found, the rest of the line is | passed to system()-call. | = line got -> TRUE, EOF -> FALSE ! There should be a way to get an echo when reading from file. & fprintf(), isatty(), fileno(), strlen(), fgets(), system() ^=====================================================================*/ { char *ptr = buff, *p; /* Can't get rid of these. */ if ( !math_in ) return FALSE; /* Try figuring out if input & output streams are terminals, if they both are, give user a prompt. */ if (isatty(fileno(math_in)) && isatty(fileno(math_out))) PrintOut( "%s", prompt ); /* i'm not in the mood to explain this. */ *ptr++ = ' '; /* Go for it. */ while((ptr = fgets(ptr, 256, math_in)) != NULL) { ptr[strlen(ptr)-1] = '\0'; /* * Check if the user wants to continue with this line. */ while(ptr[strlen(ptr)-1] == '\\') { ptr += strlen(ptr) - 1; dogets(ptr, PMODE_CONT); } /* * if there is only spaces in this line, * don't bother returning it, instead * let's read afresh, otherwise return. */ p = ptr; while(isspace(*p)) p++; if (*p != '\0') /* GOOD EXIT HERE */ { #if 0 /* * Look for the system character, if found * pass rest of the line to system()-call */ for(p = buff; *p; p++) { switch(*p) { case SYSTEM: system(p + 1); PrintOut("\n"); *p = '\0'; p--; break; } } #endif if (*buff != '\0') return TRUE; /* OR IF WE ARE HONEST, IT'S HERE */ } /* if it's terminal give a prompt. */ if (isatty(fileno(math_in)) && isatty(fileno(math_out))) PrintOut("%s", prompt); } return FALSE; } void com_init(word, flag_pw, flag_ce, sub, minp, maxp, help_text ) /*====================================================================== ? Adds commands to global command list. | | Parameters: | char *word | - the keyword user gives for this command to be executed. | int flag_pw | - flag telling if the command can be executed element | by element using function *(*sub)(). | int flag_ce | - flag telling if the command can be executed when | preprosessing if constant arguments | double *(*sub)() | - function to be executed when this command is given | int minp, maxp | - maximum and minimum number of parameters to command | | The global list of available commands is updated (or created if | nonexistent). | & lst_add() ~ *_com_init() ^=====================================================================*/ char *word; VARIABLE *(*sub)(); int minp, maxp, flag_pw, flag_ce; char *help_text; { COMMAND *ptr; /* can't get rid of this */ /* Fill the structure... */ ptr = (COMMAND *)ALLOCMEM(COMSIZE); NAME(ptr) = STRCOPY(word); if (flag_pw) ptr->flags |= CMDFLAG_PW; if (flag_ce) ptr->flags |= CMDFLAG_CE; ptr->minp = minp; ptr->maxp = maxp; ptr->sub = sub; ptr->help = help_text; /* ...and update the list. */ lst_add(COMMANDS, (LIST *)ptr); return; } void com_free() /*====================================================================== ? Deletes the list of commands and frees associated memory. | & lst_purge() ^=====================================================================*/ { /* Give memory back to system */ lst_purge(COMMANDS); return; } COMMAND *com_check(str) char *str; /*====================================================================== ? Look for command from COMMANDS list by name. | = COMMAND *NULL if does not exist, pointer to command otherwise & lst_find() ^=====================================================================*/ { return (COMMAND *)lst_find(COMMANDS, str); } VARIABLE *com_help( VARIABLE *ptr ) /*====================================================================== ? Print list of commands and user defined functions from global lists. | ! The command to get here is "help" but it really is not very helpful. | & lst_print() ^=====================================================================*/ { COMMAND *cmd; FUNCTION *fnc; char *name; if ( !ptr ) { lst_print(COMMANDS); lst_print(FUNCTIONS); } else { name = var_to_string( ptr ); if ( (cmd = com_check( name ) ) != (COMMAND *)NULL ) { if ( cmd->help ) PrintOut( "\n%s\n", cmd->help ); else PrintOut( "\nSorry: no help available on [%s].\n", name ); } else if ( (fnc = fnc_check( name ) ) != (FUNCTION *)NULL ) { if ( fnc->help ) PrintOut( "\n%s", fnc->help ); else PrintOut( "\nSorry: no help available on [%s].\n", name ); } else { error( "help: symbol not found: [%s]\n", name ); } FREEMEM( name ); } return (VARIABLE *)NULL; } VARIABLE *com_pointw(sub, ptr) double (*sub)(); VARIABLE *ptr; /*====================================================================== ? This routine does a function call (*sub)(), for each element in | matrix given by ptr. | = a temporay VARIABLE for which M(res, i, j) = (*sub)(M(ptr, i, j) & var_temp_new(), *(sub)() ^=====================================================================*/ { VARIABLE *res,*ptr2; /* pointer to result structure */ double *a, *a2, *a3, *b; /* pointer to matrices */ int n, m, sz; /* matrix dimensions */ int i; /* loop index */ /* Get space for result and ... */ n = NROW(ptr); m = NCOL(ptr); res = var_temp_new(TYPE(ptr) ,n , m); sz = n*m; a = MATR(ptr); b = MATR(res); /* ...to action. */ ptr2 = NEXT(ptr); if(ptr2) { if(n!=NROW(ptr2)||m!=NCOL(ptr2)) { error("Pointwise function arguments must all be of same size."); } a2 = MATR(ptr2); ptr2 = NEXT(ptr2); if(ptr2) { if(n!=NROW(ptr2)||m!=NCOL(ptr2)) { error("Pointwise function arguments must all be of same size,"); } if(NEXT(ptr2)) { error("Currently at most three arguments for pointwise functions allowd,sorry."); } a3 = MATR(ptr2); for(i = 0; i < sz; i++) *b++ = (*sub)(*a++,*a2++,*a3++); } else { for(i = 0; i < sz; i++) *b++ = (*sub)(*a++,*a2++); } } else { for(i = 0; i < sz; i++) *b++ = (*sub)(*a++); } return res; } VARIABLE *com_el(ptr) VARIABLE *ptr; /*====================================================================== ? Extracts specified elements from a matrix. Indexes are given by two | column vectors. The values of the elements of these vectors give | the required indexes. If there is only one index vector given | it is assumed to be column index and row index is set to scalar 0. | | If matrix x is, for example, | | 1 2 | 3 4 | | you get the first row by | | x[0, 0 1] | | or by | | x(0 1) | = A new temporary VARIABLE, whose size equals to | number of row indexes times number of column indexes. | & var_temp_new(), var_delete_temp() ^=====================================================================*/ { VARIABLE *res, /* result ... */ *par = NEXT(ptr); /* pointer to list of VARIABLES */ /* containig indexes */ static double defind = 0.0; #pragma omp threadprivate (defind) double *ind1 = &defind, *ind2; int i, j, k, /* loop indexes */ rows, cols, /* no. of rows and columns in the matrix */ /* to be indexed. */ size1 = 1, size2, ind; rows = NROW(ptr); cols = NCOL(ptr); /* * check if scalar .... */ if (rows == 1 && cols == 1) { if (*MATR(par) != 0) error("Index out of bounds.\n"); if (NEXT(par) != NULL) if (*MATR(NEXT(par)) != 0) error("Index out of bounds.\n"); res = var_temp_new(TYPE(ptr),1,1); *MATR(res) = *MATR(ptr); return res; } /* The matrix will be indexed by two column vectors. If there is just one assume it's column index and make rowindex 0. */ if (NEXT(par) == NULL) { if (NROW(par) == rows && NCOL(par) == cols) { int logical = TRUE, onecount=0; double *dtmp; dtmp = MATR(par); for(i = 0; i < NROW(par)*NCOL(par); i++) if (dtmp[i] == 0) { } else if (dtmp[i] == 1) { onecount++; } else { logical = FALSE; break; } if (logical) { if (onecount == 0) return NULL; res = var_temp_new(TYPE(ptr),1,onecount); for(i=0,k=0; i < rows; i++) for(j=0; j < cols; j++) if (M(par,i,j) == 1) { memcpy(&M(res,0,k++),&M(ptr,i,j),sizeof(double)); } return res; } } ind2 = MATR(par); size2 = NCOL(par); cols *= rows; rows = 1; } else { ind1 = MATR(par); size1 = NCOL(par); size2 = NCOL(NEXT(par)); ind2 = MATR(NEXT(par)); } /* Space for result */ res = var_temp_new(TYPE(ptr), size1, size2); /* Extract the values (try making sense out of that if you feel like it). */ for(i = 0; i < size1; i++) { ind = (int)ind1[i]; for(j = 0; j < size2; j++) if (ind < rows && (int)ind2[j] < cols) memcpy(&M(res,i,j),&M(ptr,ind,(int)ind2[j]),sizeof(double)); else error("Index out of bounds.\n"); } return res; } VARIABLE *com_source(ptr) VARIABLE *ptr; /*====================================================================== ? Redirect input stream to a file, whose name is given. | @ FILE *math_in & ALLOCMEM, FREEMEM, fopen(), fclose(), error() ^=====================================================================*/ { char *name; /* Hold converted string (file name) */ FILE *save_in = math_in; /* Save previous input stream until */ /* we are done with the new file. */ /* convert the file name from ptr. */ name = var_to_string(ptr); /* Execute the file. */ if ((math_in = fopen(name,"r")) != NULL) { /* PrintOut("Executing commands from file, %s...\n", name); */ doread(); fclose(math_in); } else { PrintOut( "Source: Can't open file, %s.\n",name ); } math_in = save_in; FREEMEM(name); return (VARIABLE *)NULL; } VARIABLE *com_apply(ptr) VARIABLE *ptr; /*====================================================================== ? Executes given string. | & ALLOCMEM, FREEMEM, doit() ^=====================================================================*/ { VARIABLE *res; /* result pointer */ char *p, *q; /* holds the string to be executed, after */ /* conversion from structure VARIABLE * */ int i, j; /* just loop indexes */ /* Allocate space for the string... */ p = q = ALLOCMEM(NROW(ptr) * NCOL(ptr) + 1); /* ... convert it ... */ for(i = 0; i < NROW(ptr); i++) for(j = 0; j < NCOL(ptr); j++) *p++ = (char)M(ptr,i,j); *p = '\0'; /* ... and try executing it. */ res = doit( q ); FREEMEM(q); return res; } void mem_free(void *mem) /*====================================================================== ? Free memory given by argument, and unlink it from alloction list. | Currently FREEMEM(ptr) is defined to be mem_free(ptr). | & free() ~ mem_alloc(), mem_free_all() ^=====================================================================*/ { ALLOC_LIST *lst; #ifdef DEBUG tot--; fprintf(fplog,"free addr: %d total: %d\n", ALLOC_LST(mem), tot); fflush( fplog ); #endif /* if the list is empty return */ if ( (lst = (ALLOC_LIST *)ALLOC_HEAD) == (ALLOC_LIST *)NULL ) { #if 1 /* ????? */ free( ALLOC_LST(mem) ); #else fprintf( stderr, "SHOULD THIS HAPPEN ????\n" ); #endif return; } /* * it's not the header, look if it's in list at all */ if (ALLOC_PTR(lst) != mem) { for(; NEXT(lst); lst = NEXT(lst)) { if (ALLOC_PTR(NEXT(lst)) == mem) break; } /* * item was not found from the list. free ptr and return. */ if (NEXT(lst) == (ALLOC_LIST *)NULL) { free(ALLOC_LST(mem)); return; } /* * unlink */ NEXT(lst) = NEXT(NEXT(lst)); } /* * item was the header, unlink it */ else ALLOC_HEAD = NEXT(ALLOC_HEAD); /* * and at last return memory back to system */ free(ALLOC_LST(mem)); return; } void mem_free_all() /*====================================================================== ? Free all memory allocated since last entry of doread. | (actually free all memory from list ALLOCATIONS). | ~ mem_alloc(), mem_free(), doread(), error() ^=====================================================================*/ { ALLOC_LIST *lst, *lstn; for(lst = (ALLOC_LIST *)ALLOC_HEAD; lst;) { #ifdef DEBUG tot--; fprintf(fplog,"freeall addr: %d total: %d\n", lst, tot); fflush( fplog ); #endif lstn = NEXT(lst); free( (char *)lst ); lst = lstn; } ALLOC_HEAD = (LIST *)NULL; /* security */ return; } void *mem_alloc(size) size_t size; /*====================================================================== ? Allocate memory and link it to memory allocation list. | ~ calloc(), free(), error() ^=====================================================================*/ { ALLOC_LIST *lst; /* * try allocating memory */ if ((lst = (ALLOC_LIST *)calloc(size+sizeof(ALLOC_LIST), 1)) != NULL) { NEXT(lst) = (ALLOC_LIST *)ALLOC_HEAD; ALLOC_HEAD = (LIST *)lst; } else error("Can't alloc mem.\n"); #ifdef DEBUG tot++; fprintf(fplog,"alloc addr: %d size: %d total: %d\n", lst, size, tot); fflush( fplog ); #endif return ALLOC_PTR(lst); }
matProduct2.c
/* OpenMP implementation of matrix multiplication. Each thread takes care a chunk of rows. Compile with gcc -O3 -fopenmp omp_matrixmult.c -o omp_matrixmult */ // Online source: http://users.abo.fi/mats/PP2012/examples/OpenMP/omp_critical.c // permission obtained #include <omp.h> #include <stdio.h> #include <stdlib.h> /* Number of threads used */ #define NR_THREADS 4 #ifdef _CIVL #define DEBUG 1 $input int NRA=10; // number of rows in matrix A $input int NCA=10; // number of columns in matrix A $input int NCB=10; // number of columns in matrix B #else #define DEBUG 0 #define NRA 1400 // number of rows in matrix A #define NCA 1400 // number of columns in matrix A #define NCB 1400 // number of columns in matrix B #endif int main (int argc, char *argv[]) { int tid, nthreads, i, j, k; double **a, **b, **c; double *a_block, *b_block, *c_block; double **res; double *res_block; double starttime, stoptime; a = (double **) malloc(NRA*sizeof(double *)); /* matrix a to be multiplied */ b = (double **) malloc(NCA*sizeof(double *)); /* matrix b to be multiplied */ c = (double **) malloc(NRA*sizeof(double *)); /* result matrix c */ a_block = (double *) malloc(NRA*NCA*sizeof(double)); /* Storage for matrices */ b_block = (double *) malloc(NCA*NCB*sizeof(double)); c_block = (double *) malloc(NRA*NCB*sizeof(double)); /* Result matrix for the sequential algorithm */ res = (double **) malloc(NRA*sizeof(double *)); res_block = (double *) malloc(NRA*NCB*sizeof(double)); for (i=0; i<NRA; i++) /* Initialize pointers to a */ a[i] = a_block+i*NRA; for (i=0; i<NCA; i++) /* Initialize pointers to b */ b[i] = b_block+i*NCA; for (i=0; i<NRA; i++) /* Initialize pointers to c */ c[i] = c_block+i*NRA; for (i=0; i<NRA; i++) /* Initialize pointers to res */ res[i] = res_block+i*NRA; /* A static allocation of the matrices would be done like this */ /* double a[NRA][NCA], b[NCA][NCB], c[NRA][NCB]; */ /*** Spawn a parallel region explicitly scoping all variables ***/ #pragma omp parallel shared(a,b,c,nthreads) private(tid,i,j,k) num_threads(NR_THREADS) { tid = omp_get_thread_num(); if (tid == 0) { /* Only thread 0 prints */ nthreads = omp_get_num_threads(); printf("Starting matrix multiplication with %d threads\n",nthreads); printf("Initializing matrices...\n"); } /*** Initialize matrices ***/ #pragma omp for nowait /* No need to synchronize the threads before the */ for (i=0; i<NRA; i++) /* last matrix has been initialized */ for (j=0; j<NCA; j++) a[i][j]= (double) (i+j); #pragma omp for nowait for (i=0; i<NCA; i++) for (j=0; j<NCB; j++) b[i][j]= (double) (i*j); #pragma omp for /* We synchronize the threads after this */ for (i=0; i<NRA; i++) for (j=0; j<NCB; j++) c[i][j]= 0.0; if (tid == 0) /* Thread zero measures time */ starttime = omp_get_wtime(); /* Master thread measures the execution time */ /* Do matrix multiply sharing iterations on outer loop */ /* If DEBUG is TRUE display who does which iterations */ /* printf("Thread %d starting matrix multiply...\n",tid); */ #pragma omp for for (i=0; i<NRA; i++) { if (DEBUG) printf("Thread=%d did row=%d\n",tid,i); for(j=0; j<NCB; j++) { for (k=0; k<NCA; k++) { c[i][j] += a[i][k] * b[k][j]; } } } if (tid == 0) { stoptime = omp_get_wtime(); printf("Time for parallel matrix multiplication: %3.2f s\n", stoptime-starttime); } } /*** End of parallel region ***/ starttime = omp_get_wtime(); /* Do a sequential matrix multiplication and compare the results */ for (i=0; i<NRA; i++) { for (j=0; j<NCB; j++) { res[i][j] = 0.0; for (k=0; k<NCA; k++) res[i][j] += a[i][k]*b[k][j]; } } stoptime = omp_get_wtime(); printf("Time for sequential matrix multiplication: %3.2f s\n", stoptime-starttime); /* Check that the results are the same as in the parallel solution. Actually, you should not compare floating point values for equality like this but instead compute the difference between the two values and check that it is smaller than a very small value epsilon. However, since all values in the matrices here are integer values, this will work. */ for (i=0; i<NRA; i++) { for (j=0; j<NCB; j++) { if (res[i][j] == c[i][j]) { /* Everything is OK if they are equal */ } else { printf("Different result %5.1f != %5.1f in %d %d\n ", res[i][j], c[i][j], i, j); } } } /* If DEBUG is true, print the results. Usa smaller matrices for this */ if (DEBUG) { printf("Result Matrix:\n"); for (i=0; i<NRA; i++) { for (j=0; j<NCB; j++) printf("%6.1f ", c[i][j]); printf("\n"); } } printf ("Done.\n"); exit(0); }
bopm_openmp.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <time.h> /**********************CONSTANT-DEFINITIONS*******************/ #define ONE 1 #define UNITY 1.0 #define TWO 2.0 #define ITWO 2 #define HALF 0.5 #define ERROR 1 #define BILLION 1E9 /*************************************************************/ /***********************ARGUMENT MACROS***********************/ #define MAX(x,y) ((x)>(y)) ? (x) : (y) #define SQR(x) ((x)*(x)) /*************************************************************/ /**********************ENUMERATION CONSTANTS******************/ typedef enum { CRR, /*use Cox-Ross-Rubinstein formula for probabilities*/ EQUIPROB, /*use equiprobability formula*/ }; typedef enum { EUROCALL, /*European call*/ EUROPUT, /*European put*/ AMERCALL, /*American call*/ AMERPUT, /*American put*/ }; /**************************************************************/ /**************************DATA TYPES**************************/ /*Set precision for floating-point calcuations*/ typedef float Float; /*Node: data to be stored at each node in the binary tree*/ typedef struct{ Float spot; /*hypothetical spot price*/ Float prob; /*computed probability*/ Float option; /*computed option value*/ } Node; /*TreeConst: parameters needed for building binomial tree*/ typedef struct{ Float up; /*multiplicative upward movement*/ Float down; /*multiplicatiive downward movement*/ Float prob; /*probability of upward movement*/ } TreeConst; /*Ivar: structure containing five floating-point vars for option pricing*/ typedef struct{ Float S; /*spot price*/ Float X; /*strike price*/ Float T; /*time to expiration*/ Float sigma; /*volatility*/ Float mu; /*risk-free interest rate*/ } Ivar; /***************************************************************/ /************************FUNCTION PROTOTYPES********************/ Float option_price(Ivar,long,int,int); TreeConst GetConst(Ivar,int,long); Float Max(Float,Float); /***************************************************************/ int omp_thread_count() { int n = 0; #pragma omp parallel reduction(+:n) n += 1; return n; } main(int argc,char *argv[] ){ Ivar data; int steps,num_threads; /*number of steps in tree*/ Float price; struct timespec reqStart,reqEnd; double accum; data.S = 20; /*current spot price*/ data.X = 30; /*strike price of option*/ data.T = 2.0; /*time to expiration*/ data.sigma=0.20; /*volatility*/ data.mu=0.05; /*risk-free interest rate*/ steps = atoi(argv[1]); num_threads = atoi(argv[2]); omp_set_num_threads(num_threads); printf("threads -- %d",omp_thread_count()); clock_gettime(CLOCK_REALTIME, &reqStart); price = option_price(data, steps, EUROPUT, CRR); printf("EUROPUT WITH CRR:\t%8.3f\n", price); clock_gettime(CLOCK_REALTIME, &reqEnd); accum = ( reqEnd.tv_sec - reqStart.tv_sec ) + ( reqEnd.tv_nsec - reqStart.tv_nsec ) / BILLION; printf( "\n TIME TAKEN FOR BOPM Routine : %lf\n", accum ); clock_gettime(CLOCK_REALTIME, &reqStart); price = option_price(data, steps, EUROCALL, CRR); clock_gettime(CLOCK_REALTIME, &reqEnd); printf("EUROCALL WITH CRR\t%8.3f\n", price); accum = ( reqEnd.tv_sec - reqStart.tv_sec ) + ( reqEnd.tv_nsec - reqStart.tv_nsec ) / BILLION; printf( "\n TIME TAKEN FOR BOPM Routine : %lf\n", accum ); clock_gettime(CLOCK_REALTIME, &reqStart); price = option_price(data, steps, AMERPUT, CRR); printf("AMERPUT WITH CRR\t%8.3f\n", price); clock_gettime(CLOCK_REALTIME, &reqEnd); accum = ( reqEnd.tv_sec - reqStart.tv_sec ) + ( reqEnd.tv_nsec - reqStart.tv_nsec ) / BILLION; printf( "\n TIME TAKEN FOR BOPM Routine : %lf\n", accum ); clock_gettime(CLOCK_REALTIME, &reqStart); price = option_price(data, steps, AMERCALL, CRR); printf("AMERCALL WITH CRR\t%8.3f\n", price); clock_gettime(CLOCK_REALTIME, &reqEnd); accum = ( reqEnd.tv_sec - reqStart.tv_sec ) + ( reqEnd.tv_nsec - reqStart.tv_nsec ) / BILLION; printf( "\n TIME TAKEN FOR BOPM Routine : %lf\n", accum ); return 0; } /*calculate up, down, and probability based on method used*/ TreeConst GetConst(Ivar option_data, int method, long steps){ TreeConst constants; Float mu, sigma, dt; /******DATA FOR DETERMINATION OF UP, DOWN, AND PROB******/ mu = option_data.mu; sigma = option_data.sigma; dt = option_data.T / (steps - ONE); /********************************************************/ /******COX-ROSS-RUBINSTEIN FORMULAE**********************/ if(CRR == method){ constants.up = exp(sigma * sqrt(dt)); constants.down = UNITY / constants.up; constants.prob = (exp(mu*dt) - constants.down) / (constants.up - constants.down); } /********************************************************/ /**********FAULTY VALUE FOR METHOD***********************/ else{ fprintf(stderr, "ERROR: invalid method specified\n"); exit(ERROR); } /*********************************************************/ return constants; } /*return option price*/ Float option_price( Ivar vars, /*five floating vars defined in Ivar type*/ long steps, /*number of steps in the binomial tree*/ int type, /*call / put -- American/European*/ int method /*Cox-Ross-Rubinstein or Equiprobability*/ ){ Node *tree; TreeConst constants; /*constants for CRR or EQUIPROB*/ Float up, down; /*constants for CRR or EQUIPROB*/ Float up_prob; /*constants for CRR or EQUIPROB*/ Float down_prob; /*constants for CRR or EQUIPROB*/ long StepPtr; /*dummy: step pointer*/ long SpotPtr; /*dummy: price pointer*/ Float discount; /*discount factor for one time step*/ Float price; /*value to be returned*/ Float dt; /*time step*/ Float *tmp_options,*tmp_spots; struct timespec reqStart,reqEnd; double accum; int i; /******CALCULATE DISCOUNT FACTOR FOR ONE TIME STEP********/ dt = vars.T / (steps - ONE); discount = exp(-vars.mu * dt); /*********************************************************/ /***CALCULATE APPROPRIATE CONSTANTS FOR SPECIFIED METHOD**/ constants = GetConst(vars, method, steps); up = constants.up; down = constants.down; up_prob = constants.prob; down_prob = UNITY - up_prob; /*********************************************************/ /******ALLOCATE SPACE FOR ONE STEP IN BINOMIAL TREE*******/ tree = (Node*)malloc((steps + ONE)*sizeof(Node)); if(NULL == tree){ fprintf(stderr, "ERROR: failure of malloc()\n"); exit(ERROR); } /********************************************************/ /*********FIRST INITIALIZE ZEROTH NODE*******************/ tree[0].spot = vars.S; tree[0].prob = UNITY; /*********************************************************/ tmp_options = malloc(sizeof(Float)*steps); tmp_spots = malloc(sizeof(Float)*steps); //#pragma omp parallel /*********FILL TREE WITH SPOT PRICES**********************/ //#pragma omp for for(StepPtr = ONE; StepPtr < steps; StepPtr++){ tree[StepPtr].spot = tree[StepPtr - ONE].spot * up; #pragma omp parallel for for(SpotPtr = 0; SpotPtr < StepPtr; SpotPtr++){ tree[SpotPtr].spot *= down; } }/**********************************************************/ /********FILL TREE WITH PROBABILITIES**********************/ //#pragma omp for for(StepPtr = ONE; StepPtr < steps; StepPtr++){ //calculate prob for highest spot price tree[StepPtr].prob = tree[StepPtr - ONE].prob * up_prob; //calculate prob for spot price in between* #pragma omp parallel for for(SpotPtr = StepPtr - ONE; SpotPtr > 0; SpotPtr--){ tree[SpotPtr].prob = tree[SpotPtr].prob * down_prob + tree[SpotPtr - ONE].prob * up_prob ; } //calculate prob for lowest spot price* tree[0].prob *= down_prob; } /**********************************************************/ /******CALCULATE OPTION VALUES ON EXPIRATION DATE**********/ if((EUROCALL == type)||(AMERCALL == type)){ #pragma omp parallel for for(SpotPtr = 0; SpotPtr < steps; SpotPtr++){ tree[SpotPtr].option = MAX(0.0, tree[SpotPtr].spot - vars.X); } } else if((EUROPUT == type)||(AMERPUT == type)){ #pragma omp parallel for for(SpotPtr = 0; SpotPtr < steps; SpotPtr++){ tree[SpotPtr].option = MAX(0.0, vars.X - tree[SpotPtr].spot); } } else{ fprintf(stderr, "ERROR: invalid option type\n"); exit(ERROR); } /***********************************************************/ clock_gettime(CLOCK_REALTIME, &reqStart); /*WALK BACKWARDS THROUGH BINOMIAL TREE FROM EXPIRATION TO ORIGIN*/ price=0.0; for(StepPtr = steps - ITWO; StepPtr >=0; StepPtr--){ #pragma omp parallel for for(SpotPtr = 0; SpotPtr < steps; SpotPtr++){ tmp_options[SpotPtr]=tree[SpotPtr].option; tmp_spots[SpotPtr]=tree[SpotPtr].spot; } #pragma omp parallel for for(SpotPtr = 0; SpotPtr <= StepPtr; SpotPtr++){ Float early = 0.0; /*value if exercised early*/ /*calculate weighted average*/ tree[SpotPtr].option = down_prob * tree[SpotPtr].option + up_prob * tmp_options[SpotPtr + ONE]; /*calculate spot price*/ tree[SpotPtr].spot = tmp_spots[SpotPtr+ONE] / up; /*apply discount factor*/ tree[SpotPtr].option *= discount; /*determine if early exercise is desirable*/ if(AMERCALL == type){ early = MAX(0.0, tree[SpotPtr].spot - vars.X); } else if(AMERPUT == type){ early = MAX(0.0, vars.X - tree[SpotPtr].spot); } tree[SpotPtr].option = MAX( tree[SpotPtr].option, early ); } } /*******************************************************************/ clock_gettime(CLOCK_REALTIME, &reqEnd); /*price is...*/ price = tree[0].option; accum = ( reqEnd.tv_sec - reqStart.tv_sec ) + ( reqEnd.tv_nsec - reqStart.tv_nsec ) / BILLION; printf( "\n TIME TAKEN FOR WAlkBack Routine : %lf\n", accum ); /*return the binomial tree to the memory pool and return the result*/ free(tree); return price; }
factorial.c
#include<stdio.h> #include<omp.h> #include<stdlib.h> double fact(double n) { double f=1; for (int i=1;i<n;i++) { f *= i; } return (f); } int main(int argc, char* argv[]) { double y1,y2,y; #pragma omp sections { #pragma omp section y1 = fact(1); #pragma omp section y2 = fact(4); } y = y1 + y2; printf("%f\n", y); }