source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_unaryop__minv_uint32_int32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__minv_uint32_int32 // op(A') function: GB_tran__minv_uint32_int32 // C type: uint32_t // A type: int32_t // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = GB_IMINV_UNSIGNED (aij, 32) #define GB_ATYPE \ int32_t #define GB_CTYPE \ uint32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_IMINV_UNSIGNED (x, 32) ; // casting #define GB_CASTING(z, x) \ uint32_t z = (uint32_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_UINT32 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_uint32_int32 ( uint32_t *restrict Cx, const int32_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__minv_uint32_int32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB067-restrictpointer1-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* restrict pointers: no aliasing Array initialization using assignments. C99 is needed to compile this code e.g. gcc -std=c99 -c Stress-1.c */ #include <stdlib.h> typedef double real8; void foo(real8 * restrict newSxx, real8 * restrict newSyy, int length) { int i; #pragma omp parallel for private(i) for (i = 0; i <= length - 1; i += 1) { newSxx[i] = 0.0; newSyy[i] = 0.0; } } void print(real8 * restrict newSxx, real8 * restrict newSyy, int length) { int i; for (i = 0; i <= length - 1; i += 1) { printf("%lf %lf\n", newSxx[i], newSyy[i]); } } int main() { int length=1000; real8* newSxx = malloc (length* sizeof (real8)); real8* newSyy = malloc (length* sizeof (real8)); foo(newSxx, newSyy, length); print(newSxx, newSyy, length); free (newSxx); free (newSyy); return 0; }
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] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<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,12);t1++) { lbp=max(ceild(t1,2),ceild(24*t1-Nt+3,24)); ubp=min(floord(Nt+Nz-4,24),floord(12*t1+Nz+9,24)); #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(3*t1-1,2)),ceild(24*t2-Nz-4,8));t3<=min(min(min(floord(Nt+Ny-4,8),floord(12*t1+Ny+21,8)),floord(24*t2+Ny+20,8)),floord(24*t1-24*t2+Nz+Ny+19,8));t3++) { for (t4=max(max(max(0,ceild(3*t1-7,8)),ceild(24*t2-Nz-28,32)),ceild(8*t3-Ny-28,32));t4<=min(min(min(min(floord(Nt+Nx-4,32),floord(12*t1+Nx+21,32)),floord(24*t2+Nx+20,32)),floord(8*t3+Nx+4,32)),floord(24*t1-24*t2+Nz+Nx+19,32));t4++) { for (t5=max(max(max(max(max(0,12*t1),24*t1-24*t2+1),24*t2-Nz+2),8*t3-Ny+2),32*t4-Nx+2);t5<=min(min(min(min(min(Nt-2,12*t1+23),24*t2+22),8*t3+6),32*t4+30),24*t1-24*t2+Nz+21);t5++) { for (t6=max(max(24*t2,t5+1),-24*t1+24*t2+2*t5-23);t6<=min(min(24*t2+23,-24*t1+24*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(32*t4,t5+1); ubv=min(32*t4+31,t5+Nx-2); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] = (((((((coef[0][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)]) + (coef[1][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) - 1][ (-t5+t7)][ (-t5+t8)])) + (coef[2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) - 1][ (-t5+t8)])) + (coef[3][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) - 1])) + (coef[4][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6) + 1][ (-t5+t7)][ (-t5+t8)])) + (coef[5][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7) + 1][ (-t5+t8)])) + (coef[6][ (-t5+t6)][ (-t5+t7)][ (-t5+t8)] * A[ t5 % 2][ (-t5+t6)][ (-t5+t7)][ (-t5+t8) + 1]));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_binop__second_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__second_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__second_uint32) // A*D function (colscale): GB (_AxD__second_uint32) // D*A function (rowscale): GB (_DxB__second_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__second_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__second_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__second_uint32) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint32_t // A type: uint32_t // A pattern? 1 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = bij #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ ; // true if values of A are not used #define GB_A_IS_PATTERN \ 1 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_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) \ uint32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = y ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 1 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_SECOND || GxB_NO_UINT32 || GxB_NO_SECOND_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__second_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__second_uint32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__second_uint32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint32_t uint32_t bwork = (*((uint32_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__second_uint32) ( 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 uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__second_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__second_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 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__second_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__second_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__second_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__second_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_t *) x_input)) ; uint32_t *Bx = (uint32_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = GBX (Bx, p, false) ; Cx [p] = bij ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_t *) Ax_input ; uint32_t y = (*((uint32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; ; ; Cx [p] = y ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = aij ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ 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 } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = y ; \ } GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif #endif
utils.h
/* Copyright (C) 2010 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #ifndef UTILS_H #define UTILS_H #ifndef __STDC_CONSTANT_MACROS #define __STDC_CONSTANT_MACROS #endif #include <stddef.h> #include <stdint.h> #include <assert.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #ifdef GRAPH_GENERATOR_MPI #include <mpi.h> #endif #ifdef GRAPH_GENERATOR_OMP #include <omp.h> #endif #include "splittable_mrg.h" #include "kronecker.h" #if defined(_OPENMP) #define OMP(x_) _Pragma(x_) #else #define OMP(x_) #endif #ifdef __cplusplus extern "C" { #endif #if defined(HAVE_LIBNUMA) #include <numa.h> static int numa_inited = 0; static int numa_avail = -1; void * xmalloc (size_t n) { void * out; if (!numa_inited) { OMP("omp critical") { numa_inited = 1; numa_avail = numa_available (); } } if (numa_avail) out = numa_alloc (sz); else out = malloc (sz); if (!out) { fprintf(stderr, "Out of memory trying to allocate %zu byte(s)\n", sz); abort (); } return out; } void * xcalloc (size_t n, size_t sz) { void * out; if (!numa_inited) { OMP("omp critical") { numa_inited = 1; numa_avail = numa_available (); } } if (numa_avail) { size_t to_alloc; to_alloc = n * sz; if (to_alloc < n || to_alloc < sz) { fprintf(stderr, "Allocation size out of range for %zu items of %zu byte(s)\n", n, sz); abort (); } out = numa_alloc (n * sz); #if defined(_OPENMP) #pragma omp parallel for for (size_t k = 0; k < n; ++k) memset (out + k * sz, 0, sz); #else memset (out, 0, n * sz); #endif } else out = calloc (n, sz); if (!out) { fprintf(stderr, "Out of memory trying to allocate/clear %zu items of %zu byte(s)\n", n, sz); abort (); } return out; } void xfree (void * p, size_t sz) { if (!p) return; if (numa_avail >= 0) numa_free (p, sz); else free (p); } #else void * xmalloc (size_t sz) { void * out; out = malloc (sz); if (!out) { fprintf(stderr, "Out of memory trying to allocate %zu byte(s)\n", sz); abort (); } return out; } void * xcalloc (size_t n, size_t sz) { void * out; out = calloc (n, sz); if (!out) { fprintf(stderr, "Out of memory trying to allocate/clear %zu items of %zu byte(s)\n", n, sz); abort (); } return out; } void xfree (void * p, size_t) { free (p); } #endif // void* xrealloc(void* p, size_t nbytes); /* In utils.c */ // uint_fast64_t random_up_to(mrg_state* st, uint_fast64_t n); void make_mrg_seed(uint64_t userseed1, uint64_t userseed2, uint_fast32_t* seed) { seed[0] = (uint32_t)(userseed1 & UINT32_C(0x3FFFFFFF)) + 1; seed[1] = (uint32_t)((userseed1 >> 30) & UINT32_C(0x3FFFFFFF)) + 1; seed[2] = (uint32_t)(userseed2 & UINT32_C(0x3FFFFFFF)) + 1; seed[3] = (uint32_t)((userseed2 >> 30) & UINT32_C(0x3FFFFFFF)) + 1; seed[4] = (uint32_t)((userseed2 >> 60) << 4) + (uint32_t)(userseed1 >> 60) + 1; } #ifdef __cplusplus } #endif #endif /* UTILS_H */
DRB063-outeronly1-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. */ /* Only the outmost loop can be parallelized. */ int n=100, m=100; double b[100][100]; void foo() { int i,j; #pragma omp parallel for private(j) for (i=0;i<n;i++) for (j=0;j<m-1;j++) // Be careful about bounds of j b[i][j]=b[i][j+1]; } int main() { foo(); return 0; }
graphProcessing.h
/* FINISH TEMPFLATPATH CODE AS WRITTEN, THESE FUNCTIONS WILL ONLY WORK WITH GRAPHS THAT ARE IMPLEMENTED IN THE boost NAMESPACE. */ #define LP 1 #define PERFDEBUG 0 //#define FULLDEBUG 1 #ifdef _OPENMP #include <omp.h> #endif #include <boost/regex.hpp> #include <iostream> #include <fstream> #include <string> #include <assert.h> #include <staticCFG.h> /** *@file graphProcessing.h *Brief Overview of Algorithm: *********************** *Current Implementation *********************** *This implementation uses BOOSTs graph structure to analyze the paths of the graph *The path analyzer sends the user paths to be evaluated by the "analyzePath" function that is user defined ************************** *Further Improvements: TODO ************************** @todo utilize BOOST visitors to take advantage of the BOOST graph structures abilities *************** *Contact Info *************** *Finally, blame can be assigned to and questions can be forwarded to the author, though response is not guaranteed *if I'm still at Lawrence *hoffman34 AT llnl DOT gov *@author Michael Hoffman */ #include <boost/graph/adjacency_list.hpp> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <boost/tuple/tuple.hpp> #include <boost/graph/graphviz.hpp> #include <boost/graph/dominator_tree.hpp> #include <boost/graph/reverse_graph.hpp> #include <boost/graph/transpose_graph.hpp> #include <boost/algorithm/string.hpp> #include <vector> #include <algorithm> #include <utility> #include <iostream> #include <sys/time.h> #include <sys/resource.h> #include <sys/time.h> template <class CFG> class SgGraphTraversal { public: typedef typename boost::graph_traits<CFG>::vertex_descriptor Vertex; typedef typename boost::graph_traits<CFG>:: edge_descriptor Edge; void constructPathAnalyzer(CFG* g, bool unbounded=false, Vertex end=0, Vertex begin=0, bool ns = true); virtual void analyzePath(std::vector<Vertex>& pth) = 0; std::vector<int> getInEdges(int& node, CFG*& g); std::vector<int> getOutEdges(int& node, CFG*& g); int getTarget(int& n, CFG*& g); int getSource(int& n, CFG*& g); std::map<Vertex, int> vertintmap; std::map<Edge, int> edgeintmap; std::map<int, Vertex> intvertmap; std::map<int, Edge> intedgemap; SgGraphTraversal(); virtual ~SgGraphTraversal(); SgGraphTraversal( SgGraphTraversal &); SgGraphTraversal &operator=( SgGraphTraversal &); int pathnum; void firstPrepGraph(CFG*& g); private: int normals; int abnormals; bool needssafety; int recursed; int checkedfound; // typedef typename boost::graph_traits<CFG>::vertex_descriptor Vertex; // typedef typename boost::graph_traits<CFG>:: edge_descriptor Edge; // std::vector<int> getInEdges(int& node, CFG*& g); // std::vector<int> getOutEdges(int& node, CFG*& g); void prepareGraph(CFG*& g); void findClosuresAndMarkersAndEnumerate(CFG*& g); // void constructPathAnalyzer(CFG* g, bool unbounded=false, Vertex end=0, Vertex begin=0, bool ns = true); // virtual void analyzePath(std::vector<Vertex>& pth) = 0; // void firstPrepGraph(CFG*& g); int stoppedpaths; std::set<std::vector<int> > traversePath(int begin, int end, CFG*& g, bool loop=false); std::set<std::vector<int> > uTraversePath(int begin, int end, CFG*& g, bool loop, std::map<int, std::vector<std::vector<int> > >& localLoops); std::vector<std::vector<int> > bfsTraversePath(int begin, int end, CFG*& g, bool loop=false); std::vector<int> unzipPath(std::vector<int>& path, CFG*& g, int start, int end); std::vector<int> zipPath(std::vector<int>& path, CFG*& g, int start, int end); std::vector<int> zipPath2(std::vector<int>& path, CFG*& g); void printCFGNode(int& cf, std::ofstream& o); void printCFGNodeGeneric(int& cf, std::string prop, std::ofstream& o); void printCFGEdge(int& cf, CFG*& cfg, std::ofstream& o); void printHotness(CFG*& g); void printPathDot(CFG*& g); void computeOrder(CFG*& g, const int& begin); void computeSubGraphs(const int& begin, const int &end, CFG*& g, int depthDifferential); //int getTarget(int& n, CFG*& g); //int getSource(int& n, CFG*& g); std::vector<int> sources; std::vector<int> sinks; std::vector<int> recursiveLoops; std::vector<int> recurses; std::map<int, int> ptsNum; bool borrowed; std::set<int> badloop; std::map<int, std::vector<std::vector<int> > > totalLoops; // int pathnum; std::map<int, std::string> nodeStrings; int sourcenum; unsigned long long evaledpaths; int badpaths; int workingthreadnum; bool workingthread; std::map<int, std::set<std::vector<int> > > loopStore; std::vector<std::vector<int> > pathStore; std::map<int, std::vector<int> > subpathglobal; std::map<std::vector<int>, int> subpathglobalinv; int nextsubpath; std::vector<int> orderOfNodes; // std::map<Vertex, int> vertintmap; // std::map<Edge, int> edgeintmap; // std::map<int, Vertex> intvertmap; // std::map<int, Edge> intedgemap; std::vector<std::map<Vertex, Vertex> > SubGraphGraphMap; std::vector<std::map<Vertex, Vertex> > GraphSubGraphMap; std::vector<CFG*> subGraphVector; void getVertexPath(std::vector<int> path, CFG*& g, std::vector<Vertex>& vertexPath ); void storeCompact(std::vector<int> path); int nextNode; int nextEdge; std::vector<int> markers; std::vector<int> closures; std::map<int, int> markerIndex; std::map<int, std::vector<int> > pathsAtMarkers; typedef typename boost::graph_traits<CFG>::vertex_iterator vertex_iterator; typedef typename boost::graph_traits<CFG>::out_edge_iterator out_edge_iterator; typedef typename boost::graph_traits<CFG>::in_edge_iterator in_edge_iterator; typedef typename boost::graph_traits<CFG>::edge_iterator edge_iterator; bool bound; // SgGraphTraversal(); // virtual ~SgGraphTraversal(); // SgGraphTraversal( SgGraphTraversal &); // SgGraphTraversal &operator=( SgGraphTraversal &); }; template<class CFG> SgGraphTraversal<CFG>:: SgGraphTraversal() { } template<class CFG> SgGraphTraversal<CFG> & SgGraphTraversal<CFG>:: operator=( SgGraphTraversal &other) { return *this; } #ifndef SWIG template<class CFG> SgGraphTraversal<CFG>:: ~SgGraphTraversal() { } #endif /** Gets the source of an edge SgGraphTraversal::getSource Input: @param[edge] int& integer representation of edge in question @param[g] CFG*& the CFG used */ template<class CFG> inline int SgGraphTraversal<CFG>:: getSource(int& edge, CFG*& g) { Edge e = intedgemap[edge]; Vertex v = boost::source(e, *g); return(vertintmap[v]); } /** Gets the target of an edge SgGraphTraversal::getTarget Input: @param[edge] int& integer representation of edge in quesution @param[g] the CFG*& CFG used */ template<class CFG> inline int SgGraphTraversal<CFG>:: getTarget(int& edge, CFG*& g) { Edge e = intedgemap[edge]; Vertex v = boost::target(e, *g); return(vertintmap[v]); } /** Gets out edges with integer inputs, internal use only SgGraphTraversal::getInEdges Input: @param[node] int, integer representation of the node to get the in edges from @param[g] CFG* g, CFG */ template<class CFG> std::vector<int> SgGraphTraversal<CFG>:: getInEdges(int& node, CFG*& g) { Vertex getIns = intvertmap[node]; std::vector<int> inedges; // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 in_edge_iterator i, j; #else // This does not compile. in_edge_iterator i = inedges.begin(); in_edge_iterator j = i; #endif for (boost::tie(i, j) = boost::in_edges(getIns, *g); i != j; ++i) { inedges.push_back(edgeintmap[*i]); } return inedges; } /** Gets out edges with integer inputs, internal use only SgGraphTraversal::getOutEdges Input: @param[node] int, integer representation of the node to get the out edges from @param[g] CFG* g, CFG */ template<class CFG> std::vector<int> SgGraphTraversal<CFG>:: getOutEdges(int &node, CFG*& g) { Vertex getOuts = intvertmap[node]; std::vector<int> outedges; // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 out_edge_iterator i, j; #else // This does not compile. out_edge_iterator i = outedges.begin(); out_edge_iterator j = i; #endif for (boost::tie(i, j) = boost::out_edges(getOuts, *g); i != j; ++i) { outedges.push_back(edgeintmap[*i]); } return outedges; } /** Condenses paths, currently deprecated... Input: @param[pth] std::vector<int> the original path @param[g] CFG*, the ambient graph Output: zipped path */ template<class CFG> inline std::vector<int> SgGraphTraversal<CFG>:: zipPath2(std::vector<int>& pth, CFG*& g) { std::vector<int> npth; npth.push_back(pth[0]); for (int i = 1; i < pth.size()-1; i++) { if (find(closures.begin(), closures.end(), pth[i]) != closures.end()) { npth.push_back(pth[i]); } } npth.push_back(pth.back()); return npth; } /** Condenses paths to simply the first and last node and the ordered set of edges taken at nodes with more than 1 outedge Input: @param[pth] std::vector<int>, the original path @param[g] CFG*, the ambient graph @param[start] integer representation of the first node @param[end] integer representation of the last node */ template<class CFG> std::vector<int> SgGraphTraversal<CFG>:: zipPath(std::vector<int>& pth, CFG*& g, int start, int end) { std::vector<int> subpath; std::vector<int> movepath; movepath.push_back(pth.front()); movepath.push_back(pth.back()); for (unsigned int qw = 0; qw < pth.size()-1; qw++) { if (find(markers.begin(), markers.end(), pth[qw]) != markers.end()) { std::vector<int> oeds = getOutEdges(pth[qw], g); for (unsigned int i = 0; i < oeds.size(); i++) { if (getTarget(oeds[i], g) == pth[qw+1]) { movepath.push_back(oeds[i]); } } } } return movepath; } /** unzips the paths zipped by zipPath Input: @param[pzipped] the zipped path @param[CFG] the ambient graph @param[start] the integer representation of the first node (used to check that zipPath is working correctly) @param[end] the integer representation of the end node */ template<class CFG> std::vector<int> SgGraphTraversal<CFG>:: unzipPath(std::vector<int>& pzipped, CFG*& g, int start, int end) { ROSE_ASSERT(pzipped[0] == start && (pzipped[1] == end || end == -1)); std::vector<int> zipped; for (unsigned int i = 2; i < pzipped.size(); i++) { zipped.push_back(pzipped[i]); } std::vector<int> unzipped; unzipped.push_back(start); std::vector<int> oeds = getOutEdges(start, g); if (oeds.size() == 0) { return unzipped; } for (unsigned int i = 0; i < zipped.size(); i++) { oeds = getOutEdges(unzipped.back(), g); while (oeds.size() == 1) { if (getTarget(oeds[0], g) == end && unzipped.size() != 1) { unzipped.push_back(end); return unzipped; } unzipped.push_back(getTarget(oeds[0], g)); oeds = getOutEdges(unzipped.back(), g); } if (oeds.size() == 0) { return unzipped; } if (oeds.size() > 1 && (unzipped.back() != end || (unzipped.size() == 1 && unzipped.back() == end))) { ROSE_ASSERT(getSource(zipped[i], g) == unzipped.back()); unzipped.push_back(getTarget(zipped[i], g)); } } std::vector<int> oeds2 = getOutEdges(unzipped.back(), g); if (unzipped.back() != end && oeds2.size() != 0) { while (oeds2.size() == 1 && unzipped.back() != end) { unzipped.push_back(getTarget(oeds2[0], g)); oeds2 = getOutEdges(unzipped.back(), g); } } return unzipped; } /* Example Time Example: timeval tim; gettimeofday(&tim, NULL); double t1=tim.tv_sec+(tim.tv_usec/1000000.0); do_something_long(); gettimeofday(&tim, NULL); double t2=tim.tv_sec+(tim.tv_usec/1000000.0); printf("%.6lf seconds elapsed\n", t2-t1); */ /** The function responsible for collecting all paths without loops, and all paths within lops that do not include other loops then sending those to uTraverse to assemble them into all paths with any combination of loops Input: @param[begin] integer representation of the first node @param[end] integer representation of the last node (or -1 if its not bounded) @param[g] CFG*, the ambient CFG @param[loop] boolean expressing whether or not we are calculating paths contained within a loop */ template<class CFG> std::vector<std::vector<int> > SgGraphTraversal<CFG>:: bfsTraversePath(int begin, int end, CFG*& g, bool loop) { //perfdebug allows for examining the speed of traversal #ifdef PERFDEBUG //timeval tim; //gettimeofday(&tim, NULL); //double tim1 = tim.tv_sec+(tim.tv_usec/1000000.0); #endif bool recursedloop = loop; std::map<int, std::vector<std::vector<int> > > PtP; std::set<int> nodes; std::vector<std::vector<int> > pathContainer; //std::vector<std::vector<int> > oldPaths; std::vector<int> completedLoops; std::vector<std::vector<int> > npc; std::vector<int> bgpath; bgpath.push_back(begin); pathContainer.push_back(bgpath); std::vector<std::vector<int> > newPathContainer; std::vector<std::vector<int> > paths; std::vector<int> localLoops; std::map<int, std::vector<std::vector<int> > > globalLoopPaths; //std::cout << "at the while" << std::endl; //To keep while (pathContainer.size() != 0 /*|| oldPaths.size() != 0*/) { /* unsigned int mpc = 50000; if (pathContainer.size() == 0) { unsigned int mxl = 0; if (oldPaths.size() > mpc) { mxl = mpc/2; } else { mxl = oldPaths.size(); } for (unsigned int k = 0; k < mxl; k++) { pathContainer.push_back(oldPaths.back()); oldPaths.pop_back(); } } if (pathContainer.size() > mpc) { unsigned int j = 0; while (j < mpc) { npc.push_back(pathContainer.back()); pathContainer.pop_back(); j++; } oldPaths.insert(oldPaths.end(), pathContainer.begin(), pathContainer.end()); pathContainer = npc; npc.clear(); } */ //iterating through the currently discovered subpaths to build them up for (unsigned int i = 0; i < pathContainer.size(); i++) { std::vector<int> npth = pathContainer[i]; std::vector<int> oeds = getOutEdges(npth.back(), g); std::vector<int> ieds = getInEdges(npth.back(), g); npth = pathContainer[i]; oeds = getOutEdges(npth.back(), g); if ((!recursedloop && ((bound && npth.back() == end && npth.size() != 1) || (!bound && oeds.size() == 0))) || (recursedloop && npth.back() == end && npth.size() != 1)) { std::vector<int> newpth; newpth = (pathContainer[i]); std::vector<int> movepath = newpth;//zipPath(newpth, g); if (recursedloop && newpth.back() == end && newpth.size() != 1) { paths.push_back(movepath); } else if (!recursedloop) { if (bound && newpth.size() != 1 && newpth.back() == end) { paths.push_back(movepath); } else if (!bound) { paths.push_back(movepath); } } } else { std::vector<int> oeds = getOutEdges(pathContainer[i].back(), g); for (unsigned int j = 0; j < oeds.size(); j++) { int tg = getTarget(oeds[j], g); std::vector<int> newpath = (pathContainer[i]); //we split up paths into pieces so that they don't take up a lot of memory, basically this is when we run into a path //more than once, so we attach all paths that go to that path to that particular node via PtP if (nodes.find(tg) != nodes.end() && find(newpath.begin(), newpath.end(), tg) == newpath.end() && tg != end) { if (PtP.find(tg) == PtP.end()) { std::vector<int> nv; nv.push_back(tg); newPathContainer.push_back(nv); PtP[tg].push_back(/*zipPath(*(*/newpath);//, g, newpath.front(), newpath.back())); } else { PtP[tg].push_back(/*zipPath(*/newpath);//, g, newpath.front(), newpath.back())); } } else if (find(newpath.begin(), newpath.end(), getTarget(oeds[j], g)) == newpath.end() || getTarget(oeds[j], g) == end) { newpath.push_back(tg); std::vector<int> ieds = getInEdges(tg, g); if (ieds.size() > 1) {//find(closures.begin(), closures.end(), tg) != closures.end()) { nodes.insert(tg); } newPathContainer.push_back(newpath); } else if (tg == end && recursedloop) { newpath.push_back(tg); newPathContainer.push_back(newpath); } else {//if (find(newpath.begin(), newpath.end(), tg) != newpath.end() && tg != end) { std::vector<int> ieds = getInEdges(tg, g); if (ieds.size() > 1/*find(closures.begin(), closures.end(), tg) != closures.end()*/ && find(completedLoops.begin(), completedLoops.end(), tg) == completedLoops.end() /*&& find(localLoops.begin(), localLoops.end(), tg) == localLoops.end()*/ && find(recurses.begin(), recurses.end(), tg) == recurses.end()) { localLoops.push_back(tg); nodes.insert(tg); } // else if (find(recurses.begin(), recurses.end(), tg) != recurses.end()) { // } } //else { // std::cout << "problem" << std::endl; // ROSE_ASSERT(false); // } } } } pathContainer = newPathContainer; newPathContainer.clear(); } // std::cout << "done while" << std::endl; pathContainer.clear(); std::vector<std::vector<int> > finnpts; std::vector<std::vector<int> > npts; while (true) { if (paths.size() > 1000000) { std::cout << "too many paths, consider a subgraph" << std::endl; ROSE_ASSERT(false); } //#pragma omp parallel for schedule(guided) for (unsigned int qq = 0; qq < paths.size(); qq++) { std::vector<int> pq = paths[qq]; std::vector<int> qp; int ppf = paths[qq].front(); if (PtP.find(ppf) != PtP.end()) { for (unsigned int kk = 0; kk < PtP[ppf].size(); kk++) { std::vector<int> newpath = /*unzipPath(*/PtP[ppf][kk];//, g, PtP[ppf][kk][0], PtP[ppf][kk][1]); bool good = true; if (newpath.back() == newpath.front() && newpath.front() != begin && newpath.size() > 1) { good = false; } else { // if (find(pq.begin(), pq.end(), newpath.front()) != pq.end() && newpath.front() != begin) { // good = false; // } // else { for (unsigned int kk1 = 0; kk1 < newpath.size(); kk1++) { /* if (newpath.front() == newpath.back()) { good = false; break; } else */if (find(pq.begin(), pq.end(), newpath[kk1]) != pq.end() && newpath[kk1] != begin) { good = false; break; } } //} } if (good) { newpath.insert(newpath.end(), pq.begin(), pq.end()); #pragma omp critical { npts.push_back(newpath); } } } } else { std::vector<int> ppq = pq;// zipPath(pq, g, pq.front(), pq.back()); #pragma omp critical { finnpts.push_back(ppq); } } } if (npts.size() == 0) { break; } else { paths = npts; npts.clear(); } } paths = finnpts; finnpts.clear(); for (unsigned int k = 0; k < localLoops.size(); k++) { int lk = localLoops[k]; std::vector<std::vector<int> > loopp; if (loopStore.find(localLoops[k]) != loopStore.end()) { loopp.insert(loopp.end(), loopStore[localLoops[k]].begin(), loopStore[localLoops[k]].end()); } else { std::map<int, std::vector<std::vector<int> > > localLoopPaths; completedLoops.push_back(lk); recurses.push_back(lk); loopp = bfsTraversePath(lk, lk, g, true); recurses.pop_back(); } for (unsigned int ik = 0; ik < loopp.size(); ik++) { if (find(globalLoopPaths[lk].begin(), globalLoopPaths[lk].end(), loopp[ik]) == globalLoopPaths[lk].end()) { globalLoopPaths[localLoops[k]].push_back(loopp[ik]); } } } borrowed = true; std::vector<std::vector<int> > lps2; //unsigned int maxpaths = 1000; //unsigned int pathdivisor = 1;//paths.size()/maxpaths;///paths.size(); //if (pathdivisor < 1) { //pathdivisor = 1; //maxpaths = paths.size(); // } /* for (unsigned int j = 0; j < pathdivisor+1; j++) { std::vector<std::vector<int> > npaths; std::vector<int> dummyvec; unsigned int mxpths; if (j < pathdivisor) { mxpths = maxpaths; } else { mxpths = paths.size() % pathdivisor; } for (unsigned int k = 0; k < mxpths; k++) { npaths.push_back(paths.back());//unzipPath(paths.back(), g, begin, end)); paths.pop_back(); } */ pathStore = paths; paths.clear(); if (!recursedloop) { uTraversePath(begin, end, g, false, globalLoopPaths); } else { recursed++; std::set<std::vector<int> > lps = uTraversePath(begin, end, g, true, globalLoopPaths); recursed--; for (std::set<std::vector<int> >::iterator ij = lps.begin(); ij != lps.end(); ij++) { std::vector<int> ijk = (*ij); lps2.push_back(*ij); } } //} #ifdef PERFDEBUG // timeval tim; //std::cout << "begin: " << begin << " end: " << end << std::endl; //gettimeofday(&tim, NULL); //double tim2 = tim.tv_sec+(tim.tv_usec/1000000); //double timeRet = tim2 - tim1; //std::cout << "bfs time elapsed: " << timeRet << std::endl; #endif return lps2; } /** This function calculates all the permutations of loops on paths it also throws away duplicate paths Input: @param[begin] integer representation of first node @param[end] integer representation of the final node @param[g] ambient CFG @param[globalLoopPaths] connects an integer representation of a node to all possible loops starting at that node */ template<class CFG> std::set<std::vector<int> > SgGraphTraversal<CFG>:: uTraversePath(int begin, int end, CFG*& g, bool loop, std::map<int, std::vector<std::vector<int> > >& globalLoopPaths) { //std::cout << "uTraverse" << std::endl; //int doubledpaths = 0; int newmil = 1; //#ifdef LP //if (loop && loopStore.find(begin) != loopStore.end()) { // return loopStore[begin]; //} //#endif #ifdef PERFDEBUG //timeval tim; //gettimeofday(&tim, NULL); //double t1 = tim.tv_sec+(tim.tv_usec/1000000); #endif std::set<std::vector<int> > newpaths; std::set<std::vector<int> > npaths; pathnum = 0; std::vector<int> path; std::vector<std::vector<int> > paths; int truepaths = 0; std::vector<std::vector<int> > checkpaths; std::vector<std::vector<int> > npathchecker; std::map<int, int> currents; //int nnumpaths = 0; std::set<std::vector<int> > loopPaths; //bool threadsafe = true; bool done = false; std::set<std::vector<int> > fts; //double ttfors = 0; //double tperms = 0; while (true) { //std::cout << "paths.size() " << paths.size() << std::endl; if (paths.size() > 1000000) { std::cout << "nearly 1 million paths with no loops, stopping" << std::endl; return loopPaths; std::cout << "ended early" << std::endl; } if (done || borrowed) { if (borrowed) { paths = pathStore; pathStore.clear(); } //std::cout << "paths.size(): " << paths.size() << std::endl; if (paths.size() != 0) { } else { return loopPaths; } // #pragma omp parallel // { #pragma omp parallel for schedule(guided) for (unsigned int qqq = 0; qqq < paths.size(); qqq++) { // std::cout << "pathcheck" << std::endl; //int pathevals = 0; //std::vector<int> zpt = zipPath2(paths[qqq], g); //std::set<std::vector<int> > boxpaths; std::set<std::vector<int> > movepaths; std::vector<int> path;// = paths[qqq]; path = paths[qqq];//unzipPath(paths[qqq], g, begin, end); truepaths++; int permnums = 1; std::vector<int> perms; std::vector<unsigned int> qs; std::map<int, std::vector<std::vector<int> > > localLoops; std::vector<int> takenLoops; takenLoops.push_back(path[0]); bool taken = false; //timeval timfor; int lost = 0; //gettimeofday(&timfor, NULL); //double t1for = timfor.tv_sec + (timfor.tv_usec/1000000); for (unsigned int q = 1; q < path.size()-1; q++) { //if (find(closures.begin(), closures.end(), path[q]) != closures.end()) { if (globalLoopPaths.find(path[q]) != globalLoopPaths.end() /*&& find(lloops.begin(), lloops.end(), path[q]) != lloops.end()*/ && globalLoopPaths[path[q]].size() != 0 /*&& path[q] != begin && path[q] != end*/) { for (unsigned int qp1 = 0; qp1 < globalLoopPaths[path[q]].size(); qp1++) { std::vector<int> gp = globalLoopPaths[path[q]][qp1]; //unzipPath(globalLoopPaths[path[q]][qp1],g,path[q],path[q]); // std::vector<int> zgp = zipPath2(globalLoopPaths[zpt[q]][qp1], g); for (unsigned int qp2 = 0; qp2 < takenLoops.size(); qp2++) { if (find(gp.begin(),gp.end(), takenLoops[qp2]) != gp.end()) { taken = true; } } if (!taken) { localLoops[path[q]].push_back(gp); } else { lost++; taken = false; } } if (localLoops[path[q]].size() != 0) { takenLoops.push_back(path[q]); permnums *= (localLoops[path[q]].size()+1); perms.push_back(permnums); qs.push_back(path[q]); } } } //} //if (loop) { //std::cout << "lostloop: " << lost << std::endl; //} //else { //std::cout << "lostpath: " << lost << std::endl; //} //std::cout << "endpathcheck" << std::endl; //std::cout << "rest" << std::endl; //std::cout << "permnums: " << permnums << std::endl; //gettimeofday(&timfor, NULL); //double t2for = timfor.tv_sec + (timfor.tv_usec/1000000); //double ttfor = t2for - t1for; //#pragma omp atomic //ttfors += ttfor; //std::set<std::vector<int> > movepaths2; std::set<std::vector<int> > movepathscheck; //timeval timperms; //gettimeofday(&timperms, NULL); // double t1perm = timperms.tv_sec + (timperms.tv_usec/1000000); std::vector<int> nvec; std::vector<std::vector<int> > boxpaths(permnums, nvec); //#pragma omp parallel for schedule(guided) for (int i = 1; i <= permnums; i++) { //bool goodthread = false; std::vector<int> loopsTaken; //bool stop = false; unsigned int j = 0; std::vector<int> npath; while (true) { if (j == perms.size() || perms[j] > i) { break; } else { j++; } } int pn = i; std::vector<int> pL; for (unsigned int j1 = 0; j1 <= j; j1++) { pL.push_back(-1); } for (unsigned int k = j; k > 0; k--) { int l = 1; while (perms[k-1]*l < pn) { l++; } pL[k] = l-2; pn -= (perms[k-1]*(l-1)); } pL[0] = pn-2; unsigned int q2 = 0; for (unsigned int q1 = 0; q1 < path.size(); q1++) { if (q2 < qs.size()) { if (qs.size() != 0 && (unsigned)path[q1] == qs[q2] && (size_t)q2 != pL.size()) { if (pL[q2] == -1) { npath.push_back(path[q1]); } else { // if (!stop) { npath.insert(npath.end(), localLoops[path[q1]][pL[q2]].begin(), localLoops[path[q1]][pL[q2]].end()); // } } q2++; } else { npath.push_back(path[q1]); } } else { npath.push_back(path[q1]); } } #ifdef FULLDEBUG std::cout << "path: " << std::endl; for (int qe = 0; qe < npath.size(); qe++) { std::cout << ", " << npath[qe]; } std::cout << std::endl; std::cout << "permnum: " << i << std::endl; #endif // bool addit = false; //if (!stop) { // if (loop && npath.front() == npath.back()) { // addit = true; // } // else if (!loop && bound && npath.front() == begin && npath.back() == end && npath.size() != 1) { // addit = true; // } // else if (!loop && !bound) { // addit = true; // } // if (!addit) { // std::cout << "bad path" << std::endl; // } //bool extra = false; //if (addit && !loop) { //if (movepathscheck.find(npath) == movepathscheck.end()) { //int mpc = movepathscheck.size(); //std::set<std::vector<int> > movepathspre = movepathscheck; // movepaths2.insert(npath); //movepathscheck.insert(npath); //ROSE_ASSERT(movepathscheck.size() == mpc || movepathspre.find(npath) == movepathspre.end()); //if (movepathscheck.size() == mpc) { // extra = true; // } //} //else { //#pragma omp atomic // doubledpaths++; // } //} //if (!workingthread || threadsafe) { //if ((newpaths.size() > 1 || i == permnums || threadsafe)) { // } // } // } //if (!extra) // { //if (movepaths2.size() > 0) //|| i == permnums || threadsafe) // #pragma omp critical // { boxpaths[i-1] = npath; // } // } //std::cout << "endrest" << std::endl; } evaledpaths += boxpaths.size(); if (evaledpaths > newmil*100000ull) { //std::cout << "evaledpaths: " << evaledpaths << std::endl; newmil++; } // #pragma omp critical // { if (!loop) { for (std::vector<std::vector<int> >::iterator box = boxpaths.begin(); box != boxpaths.end(); box++) { std::vector<Vertex> verts; getVertexPath((*box), g, verts); #pragma omp critical { analyzePath(verts); } } } else { #pragma omp critical { loopPaths.insert(boxpaths.begin(), boxpaths.end());; } } } } //} /* #pragma omp atomic evaledpaths++; //pathevals++; if (evaledpaths % 10000 == 0 && evaledpaths != 0) { std::cout << "evaled paths: " << evaledpaths << std::endl; } if (!loop) { std::vector<Vertex> verts; getVertexPath(npath, g, verts); #pragma omp critical { #ifdef FULLDEBUG for (unsigned int aa = 0; aa < npath.size(); aa++) { if (ptsNum.find(npath[aa]) != ptsNum.end()) { ptsNum[npath[aa]] += 1; } else { ptsNum[npath[aa]] = 1; } } #endif analyzePath(verts); } } else if (loop) { //std::vector<int> zpth = zipPath(npath, g, npath.front(), npath.back()); #pragma omp critical { loopPaths.insert(npath);//zipPath(npath, g, npath.front(), npath.back())); } } else { } } */ // movepaths2.clear(); // std::cout << "permnums: " << permnums << std::endl; // std::cout << "evaledpaths final: " << pathevals << std::endl; //gettimeofday(&timperms, NULL); //double t2perm = timperms.tv_sec+(timperms.tv_usec/1000000); //#pragma omp atomic //tperms += t2perm - t1perm; // } //} //} //} #ifdef PERFDEBUG //gettimeofday(&tim, NULL); // double t2 = tim.tv_sec+(tim.tv_usec/1000000.0); // double tperm = t2 - t1perm //double tX = t2 - t1; //std::cout << "begin: " << begin << " end: " << end << std::endl; // std::cout << "uTraverse time: " << tX << std::endl; // std::cout << "tperms: " << tperms << std::endl; // std::cout << "ttfors: " << ttfors << std::endl; // std::cout << "doubledpaths: " << doubledpaths << std::endl; #endif #ifdef LP if (loop) { #ifdef PERFDEBUG // std::cout << "loopPaths: " << loopPaths.size() << std::endl; #endif loopStore[begin] = loopPaths; } #endif return loopPaths; } } /** This is the function that is used by the user directly to start the algorithm. It is immediately available to the user SgGraphTraversal::constructPathAnalyzer Input: @param[begin] Vertex, starting node @param[end] Vertex, endnode @param[g] CFG* g, CFG calculated previously */ template<class CFG> void SgGraphTraversal<CFG>:: constructPathAnalyzer(CFG* g, bool unbounded, Vertex begin, Vertex end, bool ns) { abnormals = 0; normals = 0; if (ns) { needssafety = true; } else { needssafety = false; } checkedfound = 0; recursed = 0; nextsubpath = 0; borrowed = true; stoppedpaths = 0; evaledpaths = 0; badpaths = 0; sourcenum = 0; prepareGraph(g); workingthread = false; workingthreadnum = -1; //std::cout << "markers: " << markers.size() << std::endl; //std::cout << "closures: " << closures.size() << std::endl; //std::cout << "sources: " << sources.size() << std::endl; //std::cout << "sinks" << sinks.size() << std::endl; // printHotness(g); bool subgraph = false; if (!subgraph) { if (!unbounded) { bound = true; recursiveLoops.clear(); recurses.clear(); std::vector<std::vector<int> > spaths = bfsTraversePath(vertintmap[begin], vertintmap[end], g); // std::cout << "spaths: " << spaths.size() << std::endl; } else { std::set<int> usedsources; bound = false; std::vector<int> localLps; for (unsigned int j = 0; j < sources.size(); j++) { sourcenum = sources[j]; recursiveLoops.clear(); recurses.clear(); std::vector<std::vector<int> > spaths = bfsTraversePath(sources[j], -1, g); } } } //std::cout << "checkedfound: " << checkedfound << std::endl; printHotness(g); } /** DEPRECATED This is a function to construct subgraphs for parallelization SgGraphTraversal::computeSubGraphs Input: @param[begin] const int, starting point @param[end] const int ending point @param[g] const CFG*, control flow graph to compute @param[depthDifferential] int, used to specify how large the subgraph should be */ template<class CFG> void SgGraphTraversal<CFG>:: computeSubGraphs(const int& begin, const int &end, CFG*& g, int depthDifferential) { int minDepth = 0; int maxDepth = minDepth + depthDifferential; int currSubGraph = 0; CFG* subGraph; std::set<int> foundNodes; while (true) { Vertex begin = boost::add_vertex(*subGraphVector[currSubGraph]); GraphSubGraphMap[currSubGraph][intvertmap[orderOfNodes[minDepth]]] = intvertmap[begin]; SubGraphGraphMap[currSubGraph][intvertmap[begin]] = intvertmap[orderOfNodes[minDepth]]; for (int i = minDepth; i <= maxDepth; i++) { Vertex v = GraphSubGraphMap[currSubGraph][intvertmap[orderOfNodes[i]]]; std::vector<int> outEdges = getOutEdges(orderOfNodes[i], g); for (unsigned int j = 0; j < outEdges.size(); j++) { Vertex u; if (foundNodes.find(getTarget(outEdges[j], g)) == foundNodes.end()) { u = GraphSubGraphMap[currSubGraph][intvertmap[getTarget(outEdges[j], g)]]; } else { u = boost::add_vertex(*subGraphVector[currSubGraph]); foundNodes.insert(getTarget(outEdges[j], g)); SubGraphGraphMap[currSubGraph][u] = intvertmap[getTarget(outEdges[j], g)]; GraphSubGraphMap[currSubGraph][intvertmap[getTarget(outEdges[j], g)]] = u; } Edge edge; bool ok; boost::tie(edge, ok) = boost::add_edge(v,u,*subGraphVector[currSubGraph]); } } minDepth = maxDepth; if ((unsigned int) minDepth == orderOfNodes.size()-1) { break; } maxDepth += depthDifferential; if ((unsigned int) maxDepth > orderOfNodes.size()-1) { maxDepth = orderOfNodes.size()-1; } CFG* newSubGraph; subGraphVector.push_back(newSubGraph); currSubGraph++; } return; } /* These should NOT be used by the user. They are simply for writing interesting information on the DOT graphs of the CFG */ template<class CFG> void SgGraphTraversal<CFG>:: printCFGNodeGeneric(int &cf, std::string prop, std::ofstream& o) { std::string nodeColor = "black"; o << cf << " [label=\"" << " num:" << cf << " prop: " << prop << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n"; } template<class CFG> void SgGraphTraversal<CFG>:: printCFGNode(int& cf, std::ofstream& o) { #ifdef FULLDEBUG int pts = ptsNum[cf]; std::string nodeColor = "black"; o << cf << " [label=\"" << " pts: " << pts << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n"; #endif #ifndef FULLDEBUG std::string nodeColor = "black"; o << cf << " [label=\"" << " num:" << cf << "\", color=\"" << nodeColor << "\", style=\"" << "solid" << "\"];\n"; #endif } template<class CFG> void SgGraphTraversal<CFG>:: printCFGEdge(int& cf, CFG*& cfg, std::ofstream& o) { int src = getSource(cf, cfg); int tar = getTarget(cf, cfg); o << src << " -> " << tar << " [label=\"" << src << " " << tar << "\", style=\"" << "solid" << "\"];\n"; } template<class CFG> void SgGraphTraversal<CFG>:: printHotness(CFG*& g) { const CFG* gc = g; int currhot = 0; std::ofstream mf; std::stringstream filenam; filenam << "hotness" << currhot << ".dot"; currhot++; std::string fn = filenam.str(); mf.open(fn.c_str()); mf << "digraph defaultName { \n"; // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 vertex_iterator v, vend; edge_iterator e, eend; #else // This does not compile. vertex_iterator v = vertices(*gc).begin(); vertex_iterator vend = v; edge_iterator e = edges(*gc).begin(); edge_iterator eend = e; #endif for (boost::tie(v, vend) = vertices(*gc); v != vend; ++v) { printCFGNode(vertintmap[*v], mf); } for (tie(e, eend) = edges(*gc); e != eend; ++e) { printCFGEdge(edgeintmap[*e], g, mf); } mf.close(); } template<class CFG> void SgGraphTraversal<CFG>:: printPathDot(CFG*& g) { const CFG* gc = g; std::ofstream mf; std::stringstream filenam; filenam << "pathnums.dot"; std::string fn = filenam.str(); mf.open(fn.c_str()); mf << "digraph defaultName { \n"; vertex_iterator v, vend; edge_iterator e, eend; for (tie(v, vend) = vertices(*gc); v != vend; ++v) { if (nodeStrings.find(vertintmap[*v]) != nodeStrings.end()) { int nn = vertintmap[*v]; printCFGNodeGeneric(vertintmap[*v], nodeStrings[nn], mf); } else { printCFGNodeGeneric(vertintmap[*v], "noprop", mf); } } for (tie(e, eend) = edges(*gc); e != eend; ++e) { printCFGEdge(edgeintmap[*e], g, mf); } mf.close(); } /** This is the function that preps the graph for traversal SgGraphTraversal::prepareGraph Input: @param[g] CFG*& g, CFG calculated previously */ template<class CFG> void SgGraphTraversal<CFG>:: prepareGraph(CFG*& g) { nextNode = 1; nextEdge = 1; findClosuresAndMarkersAndEnumerate(g); } /** DEPRECATED This is the function that preps the graph for traversal, currently this one isn't used but for many traversals on one visitor may necessitate SgGraphTraversal::firstPrepGraph Input: @param[g] CFG*& g, CFG calculated previously */ template<class CFG> void SgGraphTraversal<CFG>:: firstPrepGraph(CFG*& g) { nextNode = 1; nextEdge = 1; findClosuresAndMarkersAndEnumerate(g); } /** This calculates nodes with more than one in edge or more than one out edge SgGraphTraversal::findClosuresAndMarkers Input: @param[g] CFG*& g, CFG calculated previously */ template<class CFG> void SgGraphTraversal<CFG>:: findClosuresAndMarkersAndEnumerate(CFG*& g) { // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 edge_iterator e, eend; #else edge_iterator e = edges(*g).begin(); edge_iterator eend = e; #endif for (tie(e, eend) = edges(*g); e != eend; ++e) { intedgemap[nextEdge] = *e; edgeintmap[*e] = nextEdge; nextEdge++; } // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 vertex_iterator v1, vend1; #else vertex_iterator v1 = vertices(*g).begin(); vertex_iterator vend1 = v1; #endif for (boost::tie(v1, vend1) = vertices(*g); v1 != vend1; ++v1) { vertintmap[*v1] = nextNode; intvertmap[nextNode] = *v1; nextNode++; } // DQ (4/11/2017): Fix Klockworks issue of uninitialized variables. #if 1 vertex_iterator v, vend; #else vertex_iterator v = vertices(*g).begin(); vertex_iterator vend = v; #endif for (boost::tie(v, vend) = vertices(*g); v != vend; ++v) { std::vector<int> outs = getOutEdges(vertintmap[*v], g); std::vector<int> ins = getInEdges(vertintmap[*v], g); if (outs.size() > 1) { markers.push_back(vertintmap[*v]); markerIndex[vertintmap[*v]] = markers.size()-1; for (unsigned int i = 0; i < outs.size(); i++) { pathsAtMarkers[vertintmap[*v]].push_back(getTarget(outs[i], g)); } } if (ins.size() > 1) { closures.push_back(vertintmap[*v]); } if (outs.size() == 0) { sinks.push_back(vertintmap[*v]); } if (ins.size() == 0) { sources.push_back(vertintmap[*v]); } } return; } /** DEPRECATED Currently unused but will be necessary for parallelization in progress SgGraphTraversal::computeOrder @param[g] CFG* cfg in question @parm[begin] const int, integer representation of source node */ template<class CFG> void SgGraphTraversal<CFG>:: computeOrder(CFG*& g, const int& begin) { std::vector<int> currentNodes; std::vector<int> newCurrentNodes; currentNodes.push_back(begin); std::map<int, int> reverseCurrents; orderOfNodes.push_back(begin); std::set<int> heldBackNodes; while (currentNodes.size() != 0) { for (unsigned int j = 0; j < currentNodes.size(); j++) { std::vector<int> inEdges = getInEdges(currentNodes[j], g); if (inEdges.size() > 1) { if (reverseCurrents.find(currentNodes[j]) == reverseCurrents.end()) { reverseCurrents[currentNodes[j]] = 0; } if ((unsigned int) reverseCurrents[currentNodes[j]] == inEdges.size() - 1) { heldBackNodes.erase(currentNodes[j]); reverseCurrents[currentNodes[j]]++; std::vector<int> outEdges = getOutEdges(currentNodes[j], g); for (unsigned int k = 0; k < outEdges.size(); k++) { newCurrentNodes.push_back(getTarget(outEdges[k], g)); orderOfNodes.push_back(getTarget(outEdges[k], g)); } } else if (reverseCurrents[currentNodes[j]] < reverseCurrents.size()) { reverseCurrents[currentNodes[j]]++; if (heldBackNodes.find(currentNodes[j]) == heldBackNodes.end()) { heldBackNodes.insert(currentNodes[j]); } } } else { std::vector<int> outEdges = getOutEdges(currentNodes[j], g); for (unsigned int k = 0; k < outEdges.size(); k++) { newCurrentNodes.push_back(getTarget(outEdges[k], g)); orderOfNodes.push_back(getTarget(outEdges[k], g)); } } } if (newCurrentNodes.size() == 0 && heldBackNodes.size() != 0) { for (std::set<int>::iterator q = heldBackNodes.begin(); q != heldBackNodes.end(); q++) { int qint = *q; std::vector<int> heldBackOutEdges = getOutEdges(qint, g); for (unsigned int p = 0; p < heldBackOutEdges.size(); p++) { newCurrentNodes.push_back(getTarget(heldBackOutEdges[p], g)); } } heldBackNodes.clear(); } currentNodes = newCurrentNodes; newCurrentNodes.clear(); } return; } /** Converts the path calculated by this algorithm to Vertices so users can access data SgGraphTraversal::getVertexPath @param[path] integer representation of path @param[g] CFG*, cfg in question @param[vertexPath] for some reason this can't be a return value so it is changed via pass by reference */ template<class CFG> void SgGraphTraversal<CFG>:: getVertexPath(std::vector<int> path, CFG*& g, std::vector<Vertex>& vertexPath) { for (unsigned int i = 0; i < path.size(); i++) { vertexPath.push_back(intvertmap[path[i]]); } } /** DEPRECATED Currently unused, may eventually be modified for optimal storage purposes SgGraphTraversal::storeCompact @param[compactPath] path to be compactified */ template<class CFG> void SgGraphTraversal<CFG>:: storeCompact(std::vector<int> compactPath) { return; }
tensor_convert.h
/* Copyright 2019 The Blueoil Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #ifndef DLK_TENSOR_CONVERT_H_INCLUDED #define DLK_TENSOR_CONVERT_H_INCLUDED #include "global.h" #include "tensor_view.h" #include "time_measurement.h" #include "func/impl/quantized_conv2d_kn2row.h" #include "func/impl/quantized_conv2d_tiling.h" #ifdef USE_NEON #include <arm_neon.h> #endif #ifdef _OPENMP #include <omp.h> #endif inline void convert_tensor(const TensorView<BIN_CONV_OUTPUT, MemoryLayout::HWC>& before, const TensorView<BIN_CONV_OUTPUT, MemoryLayout::ChHWCl>& after) { const auto in_shape = before.get_shape(); const auto in_height = in_shape[0]; const auto in_width = in_shape[1]; const auto out_shape = after.get_shape(); const auto channel_high = out_shape[0]; const auto channel_low = out_shape[3]; Measurement::Start("Convert Tensor"); for (std::size_t dh = 0; dh < channel_high; ++dh) for (std::size_t r = 0; r < in_height; ++r) for (std::size_t c = 0; c < in_width; ++c) for (std::size_t dl = 0; dl < channel_low; ++dl) after(dh, r, c, dl) = before(r, c, dh * channel_low + dl); Measurement::Stop(); } inline void convert_tensor(const TensorView<QUANTIZED_PACKED, MemoryLayout::HWChBCl>& before, const TensorView<QUANTIZED_PACKED, MemoryLayout::ChHWBCl>& after) { const auto in_shape = before.get_shape(); const auto height = in_shape[0]; const auto width = in_shape[1]; const auto channel = in_shape[2]; const auto bits = in_shape[3]; Measurement::Start("Convert Tensor"); #pragma omp parallel for for (std::size_t i = 0; i < height; ++i) for (std::size_t j = 0; j < width; ++j) for (std::size_t k = 0; k < channel; ++k) { const auto idx_before = i * width * channel * bits + j * channel * bits + k * bits; const auto idx_after = k * height * width * bits + i * width * bits + j * bits; #ifdef AARCH32 const auto tmp = vld1_u32(reinterpret_cast<uint32_t*>(before.data() + idx_before)); vst1_u32(reinterpret_cast<uint32_t*>(after.data() + idx_after), tmp); #else *reinterpret_cast<uint64_t*>(after.data() + idx_after) = *reinterpret_cast<uint64_t*>(before.data() + idx_before); #endif } Measurement::Stop(); } inline void convert_tensor(const TensorView<QUANTIZED_PACKED, MemoryLayout::ChHWBCl>& before, const TensorView<QUANTIZED_PACKED, MemoryLayout::HWChBCl>& after) { const auto in_shape = before.get_shape(); const auto height = in_shape[1]; const auto width = in_shape[2]; const auto channel = in_shape[0]; const auto bits = in_shape[3]; Measurement::Start("Convert Tensor"); #pragma omp parallel for for (std::size_t i = 0; i < height; ++i) for (std::size_t j = 0; j < width; ++j) for (std::size_t k = 0; k < channel; ++k) { const auto idx_before = k * height * width * bits + i * width * bits + j * bits; const auto idx_after = i * width * channel * bits + j * channel * bits + k * bits; #ifdef AARCH32 const auto tmp = vld1_u32(reinterpret_cast<uint32_t*>(before.data() + idx_before)); vst1_u32(reinterpret_cast<uint32_t*>(after.data() + idx_after), tmp); #else *reinterpret_cast<uint64_t*>(after.data() + idx_after) = *reinterpret_cast<uint64_t*>(before.data() + idx_before); #endif } Measurement::Stop(); } inline void convert_tensor(const TensorView<QUANTIZED_NOT_PACKED, MemoryLayout::NHWC>& before, const dlk::impl::tiling_input_t& after) { dlk::impl::pack_input_for_tiling(before, after); } template <typename T, MemoryLayout layout> void convert_tensor(const TensorView<T, layout>& before, const TensorView<T, layout>& after) { const auto num_elems = before.size(); Measurement::Start("Convert Tensor"); #ifdef _OPENMP const auto num_threads = omp_get_max_threads(); const auto chunk_size = (num_elems + num_threads - 1) / num_threads; #pragma omp parallel for for (int i = 0; i < num_elems; i += chunk_size) { std::copy(before.data() + i, before.data() + std::min(i + chunk_size, num_elems), after.data() + i); } #else std::copy(before.data(), before.data() + num_elems, after.data()); #endif Measurement::Stop(); } #endif
GB_binop__isge_int32.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__isge_int32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__isge_int32) // A.*B function (eWiseMult): GB (_AemultB_03__isge_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_int32) // A*D function (colscale): GB (_AxD__isge_int32) // D*A function (rowscale): GB (_DxB__isge_int32) // C+=B function (dense accum): GB (_Cdense_accumB__isge_int32) // C+=b function (dense accum): GB (_Cdense_accumb__isge_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_int32) // C=scalar+B GB (_bind1st__isge_int32) // C=scalar+B' GB (_bind1st_tran__isge_int32) // C=A+scalar GB (_bind2nd__isge_int32) // C=A'+scalar GB (_bind2nd_tran__isge_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_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) \ int32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISGE || GxB_NO_INT32 || GxB_NO_ISGE_INT32) //------------------------------------------------------------------------------ // 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__isge_int32) ( 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__isge_int32) ( 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__isge_int32) ( 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 int32_t int32_t bwork = (*((int32_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__isge_int32) ( 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 int32_t *restrict Cx = (int32_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__isge_int32) ( 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 int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_int32) ( 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__isge_int32) ( 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__isge_int32) ( 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__isge_int32) ( 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__isge_int32) ( 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__isge_int32) ( 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 int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_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 ; int32_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isge_int32) ( 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 ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__isge_int32) ( 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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_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) \ { \ int32_t aij = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__isge_int32) ( 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 int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
DRB093-doall2-collapse-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. */ /* Two-dimensional array computation: collapse(2) is used to associate two loops with omp for. The corresponding loop iteration variables are private. */ #include <stdio.h> int a[100][100]; int main() { int i,j; #pragma omp parallel for for (i=0;i<100;i++) #pragma omp parallel for for (j=0;j<100;j++) a[i][j] = i; #pragma omp parallel for collapse(2) for (i=0;i<100;i++) for (j=0;j<100;j++) a[i][j]=a[i][j]+1; for (i=0;i<100;i++) for (j=0;j<100;j++) printf("%d\n", a[i][j]); return 0; }
format_trans.h
#ifndef FORMAT_TRANS #define FORMAT_TRANS #include"common.h" #include"mmio_highlevel.h" //#include"mmio.h" #include"utils.h" //calculate the number of non-empty tiles of matrix A void step1_kernel(Beidou_Tile_Matrix *matrix) // (int m, int n, MAT_PTR_TYPE *rowpointer, int *columnidx, // int tilem, int tilen, MAT_PTR_TYPE *tile_ptr, int *numtile) { int *rowpointer=matrix->rowpointer; int m = matrix->m; int n = matrix->n; int *columnidx = matrix->columnidx; int tilem = matrix->tilem; int tilen = matrix->tilen; MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr; int numtile = matrix->numtile; unsigned thread = omp_get_max_threads(); printf("threads=%i\n",thread); char *flag_g=(char *)malloc(thread*tilen * sizeof(char)); #pragma omp parallel for for (int blki = 0; blki < tilem; blki ++) { int thread_id = omp_get_thread_num(); // printf("id =%d\n",thread_id); char *flag = flag_g+ thread_id * tilen; memset(flag,0,tilen * sizeof(char)); int start = blki *BLOCK_SIZE; int end = blki == tilem-1 ? m : (blki+1)* BLOCK_SIZE ; for (int j = rowpointer[start]; j < rowpointer[end]; j ++) { int jc = columnidx[j] / BLOCK_SIZE; if (flag[jc]==0) { flag[jc]=1; tile_ptr[blki]++; } } // free(flag); } free(flag_g); } void step2_kernel(Beidou_Tile_Matrix *matrix) // (int rowA, int coA, int *rowpointerA, int *columnindexA, // int tilem, int tilenA, MAT_PTR_TYPE *tile_ptr, int *tile_columnidx, int numtileA) { int *rowpointer=matrix->rowpointer; int *columnidx = matrix->columnidx; int m = matrix->m; int n = matrix->n; int tilem = matrix->tilem; int tilen = matrix->tilen; MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr; int numtile = matrix->numtile; int *tile_columnidx = matrix->columnidx; int colid =0; char *flag=(char *)malloc(tilen * sizeof(char)); for (int i=0;i<tilem;i++) { memset(flag,0,tilen*sizeof(char)); int start= i*BLOCK_SIZE; int end = i== tilem-1 ? m : (i+1)*BLOCK_SIZE ; for (int j=rowpointer[start];j< rowpointer[end];j++) { int jc=columnidx[j]/BLOCK_SIZE; if (flag[jc]==0) { flag[jc]=1; tile_ptr[i+1]++; tile_columnidx[colid]=jc; colid++; } } } for (int i=1;i<tilem+1;i++) { tile_ptr[i] += tile_ptr[i-1]; } } //determine the tile structure (tileptr , tile columnidx and tile_nnz) of matrix A. void step2_kernel_new (Beidou_Tile_Matrix *matrix, unsigned char *tile_csr_ptr) // (int m, int n, int *rowpointer, int *columnidx, // int tilem, int tilen, MAT_PTR_TYPE *tile_ptr, int *tile_columnidx, int *tile_nnz, // unsigned char *tile_csr_ptr, int numtile) { int m = matrix->m; int n = matrix->n; int *rowpointer=matrix->rowpointer; int *columnidx = matrix->columnidx; int tilem = matrix->tilem; int tilen = matrix->tilen; MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr; int *tile_columnidx = matrix->tile_columnidx; int *tile_nnz = matrix->tile_nnz; int numtile = matrix->numtile; unsigned thread = omp_get_max_threads(); char *col_temp_g=(char *)malloc((thread * tilen) * sizeof(char)); int *nnz_temp_g=(int *)malloc((thread * tilen) * sizeof(int)); unsigned char *ptr_per_tile_g = (unsigned char *)malloc((thread * tilen * BLOCK_SIZE) * sizeof(unsigned char)); #pragma omp parallel for for (int blki = 0; blki < tilem; blki ++) { int thread_id = omp_get_thread_num(); char *col_temp = col_temp_g + thread_id * tilen; memset(col_temp,0,tilen * sizeof(char)); int *nnz_temp = nnz_temp_g + thread_id * tilen; memset(nnz_temp,0,tilen * sizeof(int)); unsigned char *ptr_per_tile = ptr_per_tile_g + thread_id * tilen * BLOCK_SIZE; memset(ptr_per_tile, 0, tilen * BLOCK_SIZE * sizeof(unsigned char)); int pre_tile = tile_ptr[blki]; int rowlen = blki==tilem-1 ? m-(tilem-1)*BLOCK_SIZE : BLOCK_SIZE ; int start= blki * BLOCK_SIZE; int end = blki==tilem-1 ? m : (blki +1)*BLOCK_SIZE ; for (int ri=0 ; ri < rowlen ; ri ++) { for (int j=rowpointer[start + ri];j<rowpointer[start + ri +1];j++) { int jc = columnidx[j]/BLOCK_SIZE; col_temp[jc] = 1; nnz_temp[jc] ++; ptr_per_tile[jc * BLOCK_SIZE + ri] ++; } } int count =0; for (int blkj=0 ;blkj < tilen; blkj++) { if (col_temp[blkj] == 1) { tile_columnidx[pre_tile + count] = blkj; tile_nnz[pre_tile + count] = nnz_temp[blkj]; for (int ri =0; ri < rowlen ; ri ++) { tile_csr_ptr[(pre_tile + count) * BLOCK_SIZE + ri] = ptr_per_tile[blkj * BLOCK_SIZE + ri]; } count ++; } } } free(col_temp_g); free(nnz_temp_g); free(ptr_per_tile_g); } void step3_kernel_new(Beidou_Tile_Matrix *matrix, int *new_coocount) { int *rowpointer=matrix->rowpointer; int *columnidx = matrix->columnidx; int m = matrix->m; int n = matrix->n; int tilem = matrix->tilem; int tilen = matrix->tilen; MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr; int numtile = matrix->numtile; int *tile_columnidx = matrix->tile_columnidx; int *tile_nnz = matrix->tile_nnz; char *Format = matrix->Format; int *blknnz = matrix->blknnz; char *blkwidth = matrix->blkwidth; int *denserowptr = matrix->denserowptr; int *densecolptr = matrix->densecolptr; unsigned char *tile_csr_ptr = matrix->csr_ptr; int *hyb_coocount = matrix->hyb_coocount; int *csr_offset = matrix->csr_offset; int *csrptr_offset = matrix->csrptr_offset; int *coo_offset = matrix->coo_offset; int *ell_offset = matrix->ell_offset; int *hyb_offset = matrix->hyb_offset; int *dns_offset = matrix->dns_offset; int *dnsrow_offset = matrix->dnsrow_offset; int *dnscol_offset = matrix->dnscol_offset; #pragma omp parallel for for (int blki=0;blki<tilem;blki++) { int tilenum_per_row=tile_ptr[blki+1]-tile_ptr[blki]; int rowlen= blki==tilem-1 ? m-(tilem-1)*BLOCK_SIZE : BLOCK_SIZE ; for (int bi=0;bi<tilenum_per_row;bi++) { int collen = tile_columnidx[tile_ptr[blki]+bi] == tilen-1 ? n - (tilen-1 ) * BLOCK_SIZE : BLOCK_SIZE ; int tile_id = tile_ptr[blki]+bi; int tilennz = tile_nnz[tile_id +1] - tile_nnz[tile_id]; int nnzthreshold = rowlen * collen * 0.5 ; // if (1) // { // Format[tile_id] =0 ; // blknnz[tile_id] = tilennz ; // csr_offset[tile_id] = tilennz; // csrptr_offset[tile_id] = rowlen; // } if (tilennz >= nnzthreshold) //if the number of nnz is more than 128, then dense { Format[tile_id] = 4 ; blknnz[tile_id] = rowlen * collen; dns_offset[tile_id] = rowlen * collen; continue; } if (tilennz <= COO_THRESHOLD) //else if the number of nnz is less than 12, then coo { Format[tile_id] = 1 ; blknnz[tile_id] = tilennz; coo_offset[tile_id] = tilennz; new_coocount[tile_id] = tilennz; continue; } else if (tilennz % collen ==0 || tilennz % rowlen ==0) { int dnsrowflag =0 ; int numdnsrow =0; int dnscolflag =0; int numdnscol =0; for (int ri=0;ri < rowlen ;ri++) { if (tile_csr_ptr[tile_id * BLOCK_SIZE + ri] % collen !=0) { dnsrowflag =0; break; } else { if (tile_csr_ptr[tile_id * BLOCK_SIZE + ri] == collen) { dnsrowflag =1; numdnsrow ++ ; } } } if (dnsrowflag == 1) { Format[tile_id] = 5 ; //Dense Row denserowptr[tile_id] = numdnsrow ; blknnz[tile_id] = numdnsrow * collen; dnsrow_offset[tile_id] = numdnsrow * collen; continue; } else { int start = blki*BLOCK_SIZE; int end = blki==tilem-1 ? m : (blki+1)*BLOCK_SIZE ; int jc = tile_columnidx[tile_id]; unsigned char *dnscol_colidx_temp= (unsigned char *)malloc(tilennz * sizeof(unsigned char)); memset(dnscol_colidx_temp, -1, tilennz * sizeof(unsigned char)); // int k=0; unsigned char *col_flag =(unsigned char *)malloc(collen * sizeof(unsigned char)); memset(col_flag, 0, collen * sizeof(unsigned char)); for (int blkj = rowpointer[start]; blkj < rowpointer[end]; blkj ++) { int jc_temp = columnidx[blkj]/BLOCK_SIZE; if (jc_temp == jc) { int col_temp = columnidx[blkj] - jc * BLOCK_SIZE; col_flag[col_temp] ++; // dnscol_colidx_temp[k]= columnindexA[blkj] - jc * BLOCK_SIZE; // if (tile_id == 389) // printf("colidx = %i\n", dnscol_colidx_temp[k]); // k++; } } for (int j =0; j < collen; j ++) { if (col_flag[j] % rowlen !=0) { dnscolflag =0; break; } else { if (col_flag[j] == rowlen) { dnscolflag =1; numdnscol ++ ; } } } if (dnscolflag == 1) { // printf("numdnscol = %i\n", numdnscol); Format[tile_id] = 6 ; //Dense Col densecolptr[tile_id] = numdnscol ; blknnz[tile_id] = numdnscol * rowlen; dnscol_offset[tile_id] = numdnscol * rowlen; continue; } // unsigned char *trans_ptr= (unsigned char *)malloc(collen * sizeof(unsigned char)); // memset(trans_ptr, 0, collen * sizeof(unsigned char)); // for (int ni =0; ni < tilennz; ni ++) // { // int coltemp = dnscol_colidx_temp[ni]; // trans_ptr[coltemp]++; // } // for (int ri=0;ri < rowlen ;ri++) // { // if (trans_ptr[ri] % rowlen !=0) // { // dnscolflag =0; // break; // } // else // { // if (trans_ptr[ri] == rowlen) // { // dnscolflag =1; // numdnscol ++ ; // } // } // } // if (dnscolflag == 1) // { // // printf("numdnscol = %i\n", numdnscol); // Format[tile_id] = 6 ; //Dense Col // densecolptr[tile_id] = numdnscol ; // blknnz[tile_id] = numdnscol * rowlen; // dnscol_offset[tile_id] = numdnscol * rowlen; // continue; // } } } if (Format[tile_id] != 5 && Format[tile_id] !=6) { int bwidth=0; for (int blkj=0;blkj<rowlen;blkj++) { if (bwidth < tile_csr_ptr[tile_id * BLOCK_SIZE + blkj] ) bwidth = tile_csr_ptr[tile_id * BLOCK_SIZE + blkj] ; } double row_length_mean = ((double)tilennz) / rowlen; double variance = 0.0; double row_length_skewness = 0.0; for (int row = 0; row < rowlen; ++row) { int length = tile_csr_ptr[tile_id * BLOCK_SIZE + row]; double delta = (double)(length - row_length_mean); variance += (delta * delta); row_length_skewness += (delta * delta * delta); } variance /= rowlen; double row_length_std_dev = sqrt(variance); row_length_skewness = (row_length_skewness / rowlen) / pow(row_length_std_dev, 3.0); double row_length_variation = row_length_std_dev / row_length_mean; double ell_csr_threshold = 0.2; double csr_hyb_threshold = 1.0; if (row_length_variation <= ell_csr_threshold) // if variation is less than 0.2, then ELL { Format[tile_id] = 2; blkwidth[tile_id]=bwidth; blknnz[tile_id] = bwidth * rowlen ; ell_offset[tile_id] = bwidth * rowlen; } else { int hybwidth=bwidth; int iopriorsize= bwidth * rowlen * sizeof (MAT_VAL_TYPE) + bwidth * rowlen * sizeof (unsigned char) ; // bwidth * rowlen * sizeof (MAT_VAL_TYPE) + bwidth * rowlen * sizeof (char) /2 +1 ; int ionextsize; int coonextnum=0; int coopriornum=0; for (int wi=bwidth-1;wi>0;wi--) { coonextnum=0; for (int blkj=0;blkj<rowlen;blkj++) { if ( tile_csr_ptr[tile_id * BLOCK_SIZE + blkj]> wi) { coonextnum += tile_csr_ptr[tile_id * BLOCK_SIZE + blkj] - wi ; } } ionextsize= wi * rowlen * sizeof (MAT_VAL_TYPE )+ wi * rowlen * sizeof (unsigned char) + coonextnum * (sizeof (MAT_VAL_TYPE) + sizeof (unsigned char)) ; // wi * rowlen * sizeof (MAT_VAL_TYPE )+ wi * rowlen * sizeof (char) /2 + 1 + coonextnum * (sizeof (MAT_VAL_TYPE) + sizeof (char)) ; if (iopriorsize<=ionextsize) { hybwidth=wi+1; break; } else { hybwidth = wi; iopriorsize=ionextsize; coopriornum=coonextnum; } } if (row_length_variation >= csr_hyb_threshold )//&& coopriornum <= 4) // if variation > 1.0, and the number of coo data <=4, then HYB { Format[tile_id] = 3; hyb_coocount[tile_id] = coopriornum; blkwidth[tile_id]=hybwidth; blknnz[tile_id] = coopriornum + hybwidth * rowlen ; hyb_offset[tile_id] = coopriornum + hybwidth * rowlen; new_coocount[tile_id] = coopriornum; } else //else CSR { Format[tile_id] =0 ; blknnz[tile_id] = tilennz ; csr_offset[tile_id] = tilennz; csrptr_offset[tile_id] = BLOCK_SIZE; } } } } } } void step4_kernel(Beidou_Tile_Matrix *matrix, unsigned char *csr_ptr, int *hyb_coocount, int nnz_temp, int tile_count_temp, int *csr_offset, int *csrptr_offset, int *coo_offset, int *ell_offset, int *hyb_offset, int *dns_offset, int *dnsrow_offset, int *dnscol_offset, MAT_VAL_TYPE *new_coo_value, int *new_coo_colidx, int *new_coo_rowidx, int *new_coocount) // (int m, int n, int *rowpointer, int *columnidx, MAT_VAL_TYPE *value, // int tilem, int tilen, int numtile, MAT_PTR_TYPE *tile_ptr, int *tile_columnidx, int *tile_nnz, char *Format, // int *blknnz, unsigned char *csr_ptr, int nnz_temp, int tile_count_temp, // MAT_VAL_TYPE *Tile_csr_Val, unsigned char *Tile_csr_Col, unsigned char *Tile_csr_Ptr, int *csr_offset, int *csrptr_offset, // MAT_VAL_TYPE *Tile_coo_Val, unsigned char *Tile_coo_colIdx, unsigned char *Tile_coo_rowIdx, int *coo_offset, // MAT_VAL_TYPE *Tile_ell_Val, unsigned char *Tile_ell_colIdx, char *blkwidth, int *ell_offset, // MAT_VAL_TYPE *Tile_hyb_Val, unsigned char *Tile_hyb_ellcolIdx, unsigned char *Tile_hyb_coorowIdx, int *hyb_coocount, int *hyb_offset, // MAT_VAL_TYPE *Tile_dns_Val, int *dns_offset, // MAT_VAL_TYPE *Tile_dnsrow_Val, char *Tile_dnsrow_idx, int * denserowptr, int *dnsrow_offset, // MAT_VAL_TYPE *Tile_dnscol_Val, char *Tile_dnscol_idx, int *densecolptr, int *dnscol_offset){ { int *rowpointer=matrix->rowpointer; int *columnidx = matrix->columnidx; MAT_VAL_TYPE *value = matrix->value; int m = matrix->m; int n = matrix->n; int tilem = matrix->tilem; int tilen = matrix->tilen; MAT_PTR_TYPE *tile_ptr = matrix->tile_ptr; int numtile = matrix->numtile; int *tile_columnidx = matrix->tile_columnidx; int *tile_nnz = matrix->tile_nnz; char *Format = matrix->Format; int *blknnz = matrix->blknnz; char *blkwidth = matrix->blkwidth; MAT_VAL_TYPE *Tile_csr_Val = matrix->Tile_csr_Val; unsigned char *Tile_csr_Col = matrix->Tile_csr_Col; unsigned char *Tile_csr_Ptr = matrix->Tile_csr_Ptr; MAT_VAL_TYPE *Tile_coo_Val = matrix->Tile_coo_Val; unsigned char *Tile_coo_colIdx = matrix->Tile_coo_colIdx; unsigned char *Tile_coo_rowIdx = matrix->Tile_coo_rowIdx; MAT_VAL_TYPE *Tile_ell_Val = matrix->Tile_ell_Val; unsigned char *Tile_ell_colIdx = matrix->Tile_ell_colIdx; MAT_VAL_TYPE *Tile_hyb_Val = matrix->Tile_hyb_Val; unsigned char *Tile_hyb_ellcolIdx = matrix->Tile_hyb_ellcolIdx; unsigned char *Tile_hyb_coorowIdx = matrix->Tile_hyb_coorowIdx; MAT_VAL_TYPE *Tile_dns_Val = matrix->Tile_dns_Val; MAT_VAL_TYPE *Tile_dnsrow_Val = matrix->Tile_dnsrow_Val; char *Tile_dnsrow_idx = matrix->Tile_dnsrow_idx; MAT_VAL_TYPE *Tile_dnscol_Val = matrix->Tile_dnscol_Val; char *Tile_dnscol_idx = matrix->Tile_dnscol_idx; int *denserowptr = matrix->denserowptr; int *densecolptr = matrix->densecolptr; unsigned short *mask = matrix->mask; unsigned thread = omp_get_max_threads(); unsigned char *csr_colidx_temp_g=(unsigned char*)malloc((thread * nnz_temp )*sizeof(unsigned char)); MAT_VAL_TYPE *csr_val_temp_g=(MAT_VAL_TYPE*)malloc((thread * nnz_temp)*sizeof(MAT_VAL_TYPE)); int *tile_count_g = (int *)malloc(thread * tile_count_temp * sizeof(int)); //for each tile #pragma omp parallel for for (int blki=0;blki<tilem;blki++) { int thread_id = omp_get_thread_num(); unsigned char *csr_colidx_temp = csr_colidx_temp_g + thread_id * nnz_temp; MAT_VAL_TYPE *csr_val_temp = csr_val_temp_g + thread_id * nnz_temp; int *tile_count = tile_count_g + thread_id * tile_count_temp; // unsigned char *csr_colidx_temp = (unsigned char *)malloc((nnz_temp )*sizeof(unsigned char)); // MAT_VAL_TYPE *csr_val_temp = (MAT_VAL_TYPE *)malloc((nnz_temp)*sizeof(MAT_VAL_TYPE)); // int *tile_count = (int *)malloc(tile_count_temp * sizeof(int)); memset(csr_colidx_temp, 0, (nnz_temp)*sizeof(unsigned char)); memset(csr_val_temp, 0, (nnz_temp)*sizeof(MAT_VAL_TYPE)); memset(tile_count, 0, (tile_count_temp)*sizeof(int)); int tilenum_per_row=tile_ptr[blki+1]-tile_ptr[blki]; int rowlen= blki==tilem-1 ? m-(tilem-1)*BLOCK_SIZE : BLOCK_SIZE ; int start = blki*BLOCK_SIZE; int end = blki==tilem-1 ? m : (blki+1)*BLOCK_SIZE ; // if (blki == 978) // { // printf("thread_id= ,tilenum_per_row=%i, nnz = %i\n", tilenum_per_row, rowpointerA[end]-rowpointerA[start]); // printf("start = %i, end = %i\n",start, end); // } for (int blkj = rowpointer[start]; blkj < rowpointer[end]; blkj ++) { int jc_temp = columnidx[blkj]/BLOCK_SIZE; // printf("blkj = %i,col=%i\n", blkj, jc_temp); for (int bi = 0; bi < tilenum_per_row; bi ++) { int tile_id = tile_ptr[blki]+bi; int jc = tile_columnidx[tile_id]; int pre_nnz = tile_nnz[tile_id] - tile_nnz[tile_ptr[blki]]; if (jc == jc_temp) { csr_val_temp[pre_nnz + tile_count[bi]] = value[blkj]; csr_colidx_temp[pre_nnz + tile_count[bi]] = columnidx[blkj] - jc * BLOCK_SIZE; // printf("tile_id = %i, tilennz = %i, jc = %i, prennz = %i, val[%i]=%f,col_before= %i, col[] = %i\n",tile_id, tilennz, jc, pre_nnz,pre_nnz + tile_count[bi],csr_val_temp[pre_nnz + tile_count[bi]], columnindexA[blkj],csr_colidx_temp[pre_nnz + tile_count[bi]]); tile_count[bi] ++; break; } } } for (int bi = 0; bi < tilenum_per_row; bi ++) { int tile_id = tile_ptr[blki]+bi; int pre_nnz = tile_nnz[tile_id] - tile_nnz[tile_ptr[blki]]; int tilennz = tile_nnz[tile_id +1] - tile_nnz[tile_id]; //blknnz[tile_id+1] - blknnz[tile_id] ; int collen = tile_columnidx[tile_id] == tilen-1 ? n - (tilen-1 ) * BLOCK_SIZE : BLOCK_SIZE ; int format = Format[tile_id]; switch (format) { case 0: { int offset = csr_offset[tile_id]; int ptr_offset = csrptr_offset[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); for (int ri =0; ri < rowlen; ri ++) { int start = ptr_temp[ri]; int stop = ri == rowlen -1 ? tilennz : ptr_temp[ ri +1];; for (int k =start; k < stop; k ++) { unsigned char colidx = csr_colidx_temp[pre_nnz + k]; Tile_csr_Val[offset + k] = csr_val_temp[pre_nnz + k]; Tile_csr_Col[offset + k] = csr_colidx_temp[pre_nnz + k]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } Tile_csr_Ptr[ptr_offset+ ri] = ptr_temp[ri]; } // for (int k = 0; k < tilennz; k++) // { // Tile_csr_Val[offset + k] = csr_val_temp[pre_nnz + k]; // Tile_csr_Col[offset + k] = csr_colidx_temp[pre_nnz + k]; // } // //CSR ptr // for (int pid=0; pid<rowlen; pid++) // { // Tile_csr_Ptr[ptr_offset+ pid] = ptr_temp[pid]; // mask[tile_id * BLOCK_SIZE + pid] |= (0x1 << (BLOCK_SIZE - colidx - 1)); // // printf("tile_csr_ptr = %i, csr_ptr = %i\n", Tile_csr_Ptr[ptr_offset+ pid] , csr_ptr[tile_id * BLOCK_SIZE + pid]); // } // unsigned char old_val = Tile_csr_Ptr[ptr_offset]; // unsigned char new_val; // Tile_csr_Ptr[ptr_offset] =0; // for (int pid =1; pid < BLOCK_SIZE; pid ++) // { // new_val = Tile_csr_Ptr[ptr_offset+pid]; // Tile_csr_Ptr[ptr_offset+pid] = old_val + Tile_csr_Ptr[ptr_offset+pid -1]; // old_val = new_val; // } break; } case 1: { if(SPMV && !SPGEMM) { // printf("do spmv operation\n"); int colidx_temp = tile_columnidx[tile_id]; int offset_new = new_coocount[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ ri +1]; for (int j = ptr_temp[ri]; j < nnz_end; j++) { new_coo_rowidx[offset_new + j] = ri + blki * BLOCK_SIZE; new_coo_value[offset_new + j] = csr_val_temp[pre_nnz + j] ; new_coo_colidx[offset_new + j]=csr_colidx_temp[pre_nnz + j] + colidx_temp * BLOCK_SIZE; } } } if(SPGEMM && !SPMV) { // printf("do spgemm operation\n"); int offset = coo_offset[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, rowlen); for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ ri +1]; for (int j = ptr_temp[ ri]; j < nnz_end; j++) { unsigned char colidx = csr_colidx_temp[pre_nnz + j]; Tile_coo_rowIdx[offset+ j] = ri; Tile_coo_Val[offset + j] = csr_val_temp[pre_nnz + j] ; Tile_coo_colIdx[offset + j]=csr_colidx_temp[pre_nnz + j]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } } break; } case 2: { int offset = ell_offset[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ri +1]; for (int j = ptr_temp[ri]; j < nnz_end; j++) { int colidx = csr_colidx_temp[pre_nnz + j]; int temp = j - ptr_temp[ri]; Tile_ell_colIdx[offset + temp * rowlen + ri] = csr_colidx_temp[pre_nnz + j]; Tile_ell_Val[offset + temp * rowlen + ri] = csr_val_temp[pre_nnz + j]; // mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } for (int ri =0; ri < rowlen; ri ++) { for (int bi = 0; bi < blkwidth[tile_id]; bi ++) { int colidx = Tile_ell_colIdx[offset + bi * rowlen + ri]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } break; } case 3: { int colidx_temp = tile_columnidx[tile_id]; int offset = hyb_offset[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); int offset_new = new_coocount[tile_id]; int coocount=0; for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ri +1]; int stop= (nnz_end- ptr_temp[ri]) <= blkwidth[tile_id] ? nnz_end : ptr_temp[ri] + blkwidth[tile_id] ; for (int j = ptr_temp[ri]; j < stop; j++) { int colidx = csr_colidx_temp[pre_nnz + j]; // printf("row = %i, j = %i, colidx = %i\n",ri,j,colidx); int temp = j - ptr_temp[ri]; Tile_hyb_ellcolIdx[offset + temp * rowlen + ri] = csr_colidx_temp[pre_nnz + j]; Tile_hyb_Val[offset + temp * rowlen + ri] = csr_val_temp[pre_nnz + j]; // mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); // printf("pos = %i, mask = %i\n", ri, mask[tile_id * BLOCK_SIZE + ri]); } if (SPGEMM && !SPMV) { for (int k=stop; k< nnz_end; k++) { unsigned char colidx = csr_colidx_temp[pre_nnz +k]; Tile_hyb_Val[offset + blkwidth[tile_id] * rowlen + coocount] = csr_val_temp[pre_nnz +k]; Tile_hyb_ellcolIdx[offset + blkwidth[tile_id] * rowlen + coocount] = csr_colidx_temp[pre_nnz +k]; Tile_hyb_coorowIdx[hyb_coocount[tile_id] + coocount] = ri; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); coocount++; } } if(SPMV && !SPGEMM) { for (int k=stop; k< nnz_end; k++) { new_coo_value[offset_new + coocount] = csr_val_temp[pre_nnz +k]; new_coo_colidx[offset_new+coocount] = csr_colidx_temp[pre_nnz +k] + colidx_temp * BLOCK_SIZE; new_coo_rowidx[offset_new+coocount] = ri + blki * BLOCK_SIZE; coocount++; } } } for (int ri =0; ri < rowlen; ri ++) { for (int bi = 0; bi < blkwidth[tile_id]; bi ++) { int colidx = Tile_hyb_ellcolIdx[offset + bi * rowlen + ri]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } break; } case 4: { int offset = dns_offset[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ri +1]; for (int j = ptr_temp[ri]; j < nnz_end; j++) { unsigned char colidx = csr_colidx_temp[pre_nnz +j]; Tile_dns_Val[offset + csr_colidx_temp[pre_nnz + j] * rowlen +ri] = csr_val_temp[pre_nnz + j]; // mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); // Blockdense_Val[dnsnum[rowblock_ptr[rbi]+bi] + subrowmatrixA[bi].columnindex[j] * rowlength + ri]= subrowmatrixA[bi].value[j]; } } for (int ri =0; ri < rowlen; ri ++) { for(int j =0; j < BLOCK_SIZE; j ++) { mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - j - 1)); } } break; } case 5: { int offset = dnsrow_offset[tile_id]; int rowoffset = denserowptr[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); int dnsriid=0; for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ri +1]; if (nnz_end - ptr_temp[ri] == collen) { // printf("tileid = %i, offset = %i, rowoffset = %i, num = %i\n", tile_id, offset, rowoffset, csr_ptr[tile_id * BLOCK_SIZE + ri]); Tile_dnsrow_idx[rowoffset + dnsriid]=ri; dnsriid ++; for (int j = ptr_temp[ri]; j < nnz_end; j++) { unsigned char colidx = csr_colidx_temp[pre_nnz +j]; Tile_dnsrow_Val[offset + j] = csr_val_temp[pre_nnz + j]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } } break; } case 6: { int offset = dnscol_offset[tile_id]; int coloffset = densecolptr[tile_id]; unsigned char *ptr_temp = csr_ptr + tile_id * BLOCK_SIZE; exclusive_scan_char(ptr_temp, BLOCK_SIZE); // for (int ni =0; ni < rowlen ; ni ++) // { // printf("%i ", ptr_temp[ni]); // } // printf("\n"); int dnsciid=0; for (int j=ptr_temp[0];j < ptr_temp[1];j ++) { int ci = csr_colidx_temp[pre_nnz + j]; // int ci = subrowmatrixA[bi].columnindex[j] ; Tile_dnscol_idx[coloffset + dnsciid] =ci ; // printf("pos=%i, colidx=%i\n",densecolptr[tile_id + dnsciid],Tile_dnscol_idx[coloffset + dnsciid] ); dnsciid++; } for (int ri = 0; ri < rowlen; ri++) { int nnz_end = ri == rowlen -1 ? tilennz : ptr_temp[ri +1]; for (int j = ptr_temp[ri]; j < nnz_end; j++) { int temp = j - ptr_temp[ri]; unsigned char colidx = csr_colidx_temp[pre_nnz +j];//temp; // if (csr_val_temp[pre_nnz +j] != 0) // printf("idx = %i, col=%i, val = %f\n",pre_nnz +j, csr_colidx_temp[pre_nnz +j] , csr_val_temp[pre_nnz +j]); Tile_dnscol_Val[offset + temp * rowlen + ri] = csr_val_temp[pre_nnz +j]; mask[tile_id * BLOCK_SIZE + ri] |= (0x1 << (BLOCK_SIZE - colidx - 1)); } } break; } default: break; } } } free(csr_colidx_temp_g); free(csr_val_temp_g); free(tile_count_g); } void Tile_destroy(Beidou_Tile_Matrix *matrix) { free(matrix->Tile_csr_Col); matrix->Tile_csr_Col = NULL; free(matrix->Tile_csr_Ptr); matrix->Tile_csr_Ptr = NULL; free(matrix->Tile_csr_Val); matrix->Tile_csr_Val = NULL; free(matrix->Tile_coo_colIdx); matrix->Tile_coo_colIdx = NULL; free(matrix->Tile_coo_rowIdx); matrix->Tile_coo_rowIdx = NULL; free(matrix->Tile_coo_Val); matrix->Tile_coo_Val = NULL; free(matrix->Tile_ell_colIdx); matrix->Tile_ell_colIdx = NULL; free(matrix->Tile_ell_Val); matrix->Tile_ell_Val = NULL; free(matrix->Tile_hyb_coorowIdx); matrix->Tile_hyb_coorowIdx = NULL; free(matrix->Tile_hyb_ellcolIdx); matrix->Tile_hyb_ellcolIdx = NULL; free(matrix->Tile_hyb_Val); matrix->Tile_hyb_Val = NULL; free(matrix->Tile_dns_Val); matrix->Tile_dns_Val = NULL; free(matrix->Tile_dnsrow_idx); matrix->Tile_dnsrow_idx = NULL; free(matrix->Tile_dnsrow_Val); matrix->Tile_dnsrow_Val = NULL; free(matrix->Tile_dnscol_Val); matrix->Tile_dnscol_Val = NULL; free(matrix->Tile_dnscol_idx); matrix->Tile_dnscol_idx = NULL; free(matrix->densecolptr); matrix->densecolptr = NULL; free(matrix->denserowptr); matrix->denserowptr = NULL; free(matrix->blkwidth); matrix->blkwidth = NULL; free(matrix->tile_ptr); matrix->tile_ptr = NULL; free(matrix->tile_columnidx); matrix->tile_columnidx = NULL; free(matrix->tile_nnz); matrix->tile_nnz = NULL; free(matrix->blknnz); matrix->blknnz = NULL; free(matrix->value); matrix->value = NULL; free(matrix->columnidx); matrix->columnidx = NULL; free(matrix->coo_new_matrix_ptr); matrix->coo_new_matrix_ptr = NULL; free(matrix->coo_new_rowidx); matrix->coo_new_rowidx = NULL; free(matrix->coo_new_matrix_value); matrix->coo_new_matrix_value = NULL; free(matrix->coo_new_matrix_colidx); matrix->coo_new_matrix_colidx = NULL; free(matrix->csr_ptr); free(matrix->csr_offset); free(matrix->csrptr_offset); free(matrix->coo_offset); free(matrix->ell_offset); free(matrix->hyb_offset); free(matrix->dns_offset); free(matrix->dnsrow_offset); free(matrix->dnscol_offset); } void format_transform(Beidou_Tile_Matrix *matrix, MAT_VAL_TYPE **new_coo_value_temp, int **new_coo_colidx_temp, int **new_coo_rowidx_temp, int **new_coocount_temp) { //unsigned char *csr_ptr = matrix->csr_ptr; // int *csr_offset = matrix->csr_offset; // int *csrptr_offset = matrix->csrptr_offset; // int *coo_offset = matrix->coo_offset; // int *ell_offset = matrix->ell_offset; // int *hyb_offset = matrix->hyb_offset; // int *dns_offset = matrix->dns_offset; // int *dnsrow_offset = matrix->dnsrow_offset; // int *dnscol_offset = matrix->dnscol_offset; // int *hyb_coocount = matrix->hyb_coocount; struct timeval t1, t2; gettimeofday(&t1, NULL); // step1_kernel(matrixA->m, matrixA->n, matrixA->rowpointer, matrixA->columnidx, // matrixA->tilem, matrixA->tilen, matrixA->tile_ptr, &matrixA->numtile); step1_kernel(matrix); gettimeofday(&t2, NULL); // printf("t1=%f,t2=%f\n",t1,t2); double time_step1 = (t2.tv_sec - t1.tv_sec) * 1000.0 + (t2.tv_usec - t1.tv_usec) / 1000.0; printf("transform_step1 runtime = %4.5f ms\n", time_step1); exclusive_scan(matrix->tile_ptr, matrix->tilem+1); matrix->numtile = matrix->tile_ptr[matrix->tilem]; printf("the number of tiles in matrix A= %d\n",matrix->numtile); matrix->tile_columnidx=(int *)malloc(matrix->numtile*sizeof(int)); memset(matrix->tile_columnidx, 0, matrix->numtile*sizeof(int)); matrix->tile_nnz = (int *)malloc((matrix->numtile + 1)* sizeof(int)); //real nnz of each sparse tile memset(matrix->tile_nnz,0,(matrix->numtile + 1) * sizeof(int)); matrix->csr_ptr = (unsigned char *)malloc((matrix->numtile * BLOCK_SIZE) * sizeof(unsigned char)); memset (matrix->csr_ptr, 0, (matrix->numtile * BLOCK_SIZE) * sizeof(unsigned char)); gettimeofday(&t1, NULL); // step2_kernel_new(matrixA->m, matrixA->n, matrixA->rowpointer, matrixA->columnidx, // matrixA->tilem, matrixA->tilen, matrixA->tile_ptr, matrixA->tile_columnidx, matrixA->tile_nnz, csr_ptr, matrixA->numtile); step2_kernel_new(matrix, matrix->csr_ptr); gettimeofday(&t2, NULL); double time_step2 = (t2.tv_sec - t1.tv_sec) * 1000.0 + (t2.tv_usec - t1.tv_usec) / 1000.0; printf("transform_step2 runtime = %4.5f ms\n", time_step2); exclusive_scan(matrix->tile_nnz, matrix->numtile +1); //format 0-7 represent 7 formats: CSR, COO, ELL, HYB, Dns, DnsRow, DnsCol matrix->Format =(char *)malloc(matrix->numtile* sizeof(char)); memset(matrix->Format,0,matrix->numtile * sizeof(char)); matrix->blknnz = (int *)malloc((matrix->numtile + 1)* sizeof(int)); //space cost that need allocate memset(matrix->blknnz,0,(matrix->numtile + 1) * sizeof(int)); //dense int dense_size=0; matrix->dns_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->dns_offset, 0, (matrix->numtile+1) * sizeof(int)); //denserow matrix->denserowptr = (int *)malloc((matrix->numtile + 1) * sizeof(int)); memset(matrix->denserowptr,0,(matrix->numtile+ 1) * sizeof(int)); int denserow_size =0 ; matrix->dnsrow_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->dnsrow_offset, 0, (matrix->numtile+1) * sizeof(int)); //densecolumn matrix->densecolptr = (int *)malloc((matrix->numtile + 1) * sizeof(int)); memset(matrix->densecolptr,0,(matrix->numtile+ 1) * sizeof(int)); int densecol_size =0 ; matrix->dnscol_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->dnscol_offset, 0, (matrix->numtile+1) * sizeof(int)); //CSR int csrsize=0; // int csrptrlen=0; matrix->csr_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->csr_offset, 0, (matrix->numtile+1) * sizeof(int)); matrix->csrptr_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->csrptr_offset, 0, (matrix->numtile+1) * sizeof(int)); //ELL int ellsize =0; matrix->ell_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->ell_offset, 0, (matrix->numtile+1) * sizeof(int)); //COO int coosize =0; matrix->coo_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->coo_offset, 0, (matrix->numtile+1) * sizeof(int)); //HYB int hybellsize =0; int hybcoosize =0; int hybsize =0; matrix->blkwidth = (char *)malloc(matrix->numtile*sizeof(char)); memset(matrix->blkwidth,0,matrix->numtile * sizeof(char)) ; matrix->hyb_coocount= (int *)malloc((matrix->numtile + 1) * sizeof(int)); memset(matrix->hyb_coocount,0,(matrix->numtile + 1) * sizeof(int)) ; matrix->hyb_offset = (int *)malloc((matrix->numtile+1) * sizeof(int)); memset(matrix->hyb_offset, 0, (matrix->numtile+1) * sizeof(int)); *new_coocount_temp = (int *)malloc((matrix->numtile + 1) * sizeof(int)); memset(*new_coocount_temp,0,(matrix->numtile + 1) * sizeof(int)) ; int *new_coocount = *new_coocount_temp; gettimeofday(&t1, NULL); // step3_kernel_new(matrixA->m, matrixA->n, matrixA->rowpointer, matrixA->columnidx, // matrixA->tilem, matrixA->tilen, matrixA->numtile, matrixA->tile_ptr, matrixA->tile_columnidx, matrixA->tile_nnz, matrixA->Format, // csr_ptr, matrixA->blknnz, matrixA->blkwidth, hyb_coocount, // matrixA->denserowptr, matrixA->densecolptr, // csr_offset, csrptr_offset, coo_offset, ell_offset, hyb_offset, dns_offset, dnsrow_offset, dnscol_offset); step3_kernel_new(matrix, new_coocount); gettimeofday(&t2, NULL); double time_step3 = (t2.tv_sec - t1.tv_sec) * 1000.0 + (t2.tv_usec - t1.tv_usec) / 1000.0; printf("transform_step3 runtime = %4.5f ms\n", time_step3); exclusive_scan(matrix->csr_offset, matrix->numtile +1); exclusive_scan(matrix->csrptr_offset, matrix->numtile +1); exclusive_scan(matrix->coo_offset, matrix->numtile +1); exclusive_scan(matrix->ell_offset, matrix->numtile +1); exclusive_scan(matrix->hyb_offset, matrix->numtile +1); exclusive_scan(matrix->dns_offset, matrix->numtile +1); exclusive_scan(matrix->dnsrow_offset, matrix->numtile +1); exclusive_scan(matrix->dnscol_offset, matrix->numtile +1); exclusive_scan(matrix->denserowptr,matrix->numtile+1); exclusive_scan(matrix->densecolptr,matrix->numtile+1); exclusive_scan(matrix->hyb_coocount, matrix->numtile +1); hybcoosize = matrix->hyb_coocount[matrix->numtile]; exclusive_scan(new_coocount, matrix->numtile +1); matrix->coocount = new_coocount[ matrix->numtile]; for (int blki=0;blki<matrix->tilem;blki++) { int rowlength= blki==matrix->tilem-1 ? matrix->m-(matrix->tilem-1)*BLOCK_SIZE : BLOCK_SIZE ; int rowbnum=matrix->tile_ptr[blki+1]-matrix->tile_ptr[blki]; for (int bi=0;bi<rowbnum;bi++) { char format= matrix->Format[matrix->tile_ptr[blki]+bi]; switch (format) { case 0: //csr csrsize += matrix->blknnz[matrix->tile_ptr[blki]+bi]; // csrptrlen += rowlength ; break; case 1: //coo coosize += matrix->blknnz[matrix->tile_ptr[blki]+bi]; break; case 2: //ell ellsize += matrix->blknnz[matrix->tile_ptr[blki]+bi] ; break; case 3: //hyb hybsize += matrix->blknnz[matrix->tile_ptr[blki]+bi]; hybellsize += matrix->blkwidth[matrix->tile_ptr[blki]+bi] * rowlength; break; case 4: dense_size += matrix->blknnz[matrix->tile_ptr[blki]+bi]; break; case 5: denserow_size += matrix->blknnz[matrix->tile_ptr[blki]+bi]; break; case 6: densecol_size += matrix->blknnz[matrix->tile_ptr[blki]+bi]; break; default: break; } } } exclusive_scan(matrix->blknnz,(matrix->numtile+1)); int *formatnum = (int *)malloc(7 * sizeof(int)); memset(formatnum,0,7 * sizeof(int)); for (int j=0;j<7;j++) { for (int i=0;i<matrix->numtile;i++) { if (matrix->Format[i]==j) { formatnum[j]++; // printf("%d ",Format[i]); // break ; } } } for (int j=0;j<7;j++) { printf("format =%i,count =%i\n",j,formatnum[j]); } int csrtilecount = formatnum[0]; int nnz_temp =0; int tile_count_temp =0; for (int blki =0;blki < matrix->tilem; blki ++) { int start= blki*BLOCK_SIZE; int end = blki==matrix->tilem-1 ? matrix->m : (blki+1)*BLOCK_SIZE ; nnz_temp = nnz_temp < matrix->rowpointer[end] - matrix->rowpointer[start] ? matrix->rowpointer[end] - matrix->rowpointer[start] : nnz_temp; tile_count_temp = tile_count_temp < matrix->tile_ptr[blki +1] - matrix->tile_ptr[blki] ? matrix->tile_ptr[blki +1] - matrix->tile_ptr[blki] : tile_count_temp; } //CSR matrix->Tile_csr_Val=(MAT_VAL_TYPE*)malloc((csrsize)*sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_csr_Val, 0, (csrsize)*sizeof(MAT_VAL_TYPE)); matrix->Tile_csr_Col=(unsigned char*)malloc((csrsize)*sizeof(unsigned char)); memset(matrix->Tile_csr_Col, 0, (csrsize)*sizeof(unsigned char)); matrix->Tile_csr_Ptr=(unsigned char*)malloc((csrtilecount * BLOCK_SIZE)*sizeof(unsigned char)); memset(matrix->Tile_csr_Ptr, 0, (csrtilecount * BLOCK_SIZE )*sizeof(unsigned char)); //COO matrix->Tile_coo_Val=(MAT_VAL_TYPE*)malloc((coosize)*sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_coo_Val, 0, (coosize)*sizeof(MAT_VAL_TYPE)); matrix->Tile_coo_colIdx=(unsigned char*)malloc((coosize)*sizeof(unsigned char)); memset(matrix->Tile_coo_colIdx, 0, (coosize)*sizeof(unsigned char)); matrix->Tile_coo_rowIdx=(unsigned char*)malloc((coosize)*sizeof(unsigned char)); memset(matrix->Tile_coo_rowIdx, 0, (coosize)*sizeof(unsigned char)); //ELL matrix->Tile_ell_Val=(MAT_VAL_TYPE*)malloc((ellsize)*sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_ell_Val,0,(ellsize)*sizeof(MAT_VAL_TYPE)); matrix->Tile_ell_colIdx=(unsigned char*)malloc((ellsize)*sizeof(unsigned char)); memset(matrix->Tile_ell_colIdx, 0, sizeof(unsigned char) * ellsize); //HYB matrix->Tile_hyb_Val=(MAT_VAL_TYPE*)malloc((hybellsize+hybcoosize)*sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_hyb_Val,0,(hybellsize+hybcoosize)*sizeof(MAT_VAL_TYPE)); matrix->Tile_hyb_ellcolIdx=(unsigned char*)malloc((hybellsize+hybcoosize)*sizeof(unsigned char)); matrix->Tile_hyb_coorowIdx=(unsigned char*)malloc((hybcoosize)*sizeof(unsigned char)) ; memset(matrix->Tile_hyb_ellcolIdx, 0, sizeof(unsigned char) * (hybellsize+hybcoosize)); memset(matrix->Tile_hyb_coorowIdx, 0, sizeof(unsigned char) * hybcoosize); //dense matrix->Tile_dns_Val=(MAT_VAL_TYPE*)malloc((dense_size)*sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_dns_Val,0,dense_size * sizeof(MAT_VAL_TYPE)); //dense row matrix->Tile_dnsrow_Val=(MAT_VAL_TYPE*)malloc((denserow_size) * sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_dnsrow_Val,0,denserow_size * sizeof(MAT_VAL_TYPE)); matrix->Tile_dnsrow_idx = (char *)malloc(matrix->denserowptr[matrix->numtile] * sizeof(char)); memset(matrix->Tile_dnsrow_idx, 0, matrix->denserowptr[matrix->numtile] * sizeof(char)); //dense column matrix->Tile_dnscol_Val=(MAT_VAL_TYPE*)malloc((densecol_size) * sizeof(MAT_VAL_TYPE)); memset(matrix->Tile_dnscol_Val, 0, densecol_size * sizeof(MAT_VAL_TYPE)); matrix->Tile_dnscol_idx = (char *)malloc(matrix->densecolptr[matrix->numtile] * sizeof(char)); memset(matrix->Tile_dnscol_idx, 0, matrix->densecolptr[matrix->numtile] * sizeof(char)); //extract COO to a new matrix matrix->coocount = hybcoosize + coosize; *new_coo_value_temp = (MAT_VAL_TYPE*)malloc(matrix->coocount *sizeof(MAT_VAL_TYPE)); memset(*new_coo_value_temp, 0, (matrix->coocount) *sizeof(MAT_VAL_TYPE)); MAT_VAL_TYPE *new_coo_value = *new_coo_value_temp; *new_coo_rowidx_temp = (int *)malloc((hybcoosize+ coosize) *sizeof(int)); memset(*new_coo_rowidx_temp, 0, (hybcoosize+coosize) *sizeof(int)); int *new_coo_rowidx = *new_coo_rowidx_temp; *new_coo_colidx_temp = (int *)malloc((matrix->coocount) *sizeof(int)); memset(*new_coo_colidx_temp, 0, (matrix->coocount) *sizeof(int)); int *new_coo_colidx = *new_coo_colidx_temp; //mask matrix->mask = (unsigned short *)malloc(matrix->numtile * BLOCK_SIZE * sizeof(unsigned short)); memset(matrix->mask, 0, matrix->numtile * BLOCK_SIZE * sizeof(unsigned short)); gettimeofday(&t1, NULL); // step4_kernel(matrixA->m, matrixA->n, matrixA->rowpointer, matrixA->columnidx, matrixA->value, // matrixA->tilem, matrixA->tilen, matrixA->numtile, matrixA->tile_ptr, matrixA->tile_columnidx, matrixA->tile_nnz, matrixA->Format, // matrixA->blknnz, csr_ptr, nnz_temp, tile_count_temp, // matrixA->Tile_csr_Val, matrixA->Tile_csr_Col, matrixA->Tile_csr_Ptr, csr_offset, csrptr_offset, // matrixA->Tile_coo_Val, matrixA->Tile_coo_colIdx, matrixA->Tile_coo_rowIdx, coo_offset, // matrixA->Tile_ell_Val, matrixA->Tile_ell_colIdx, matrixA->blkwidth, ell_offset, // matrixA->Tile_hyb_Val, matrixA->Tile_hyb_ellcolIdx, matrixA->Tile_hyb_coorowIdx, hyb_coocount, hyb_offset, // matrixA->Tile_dns_Val, dns_offset, // matrixA->Tile_dnsrow_Val, matrixA->Tile_dnsrow_idx, matrixA->denserowptr, dnsrow_offset, // matrixA->Tile_dnscol_Val, matrixA->Tile_dnscol_idx, matrixA->densecolptr, dnscol_offset); step4_kernel(matrix, matrix->csr_ptr, matrix->hyb_coocount, nnz_temp, tile_count_temp, matrix->csr_offset, matrix->csrptr_offset, matrix->coo_offset, matrix->ell_offset, matrix->hyb_offset, matrix->dns_offset, matrix->dnsrow_offset, matrix->dnscol_offset, new_coo_value,new_coo_colidx, new_coo_rowidx, new_coocount); gettimeofday(&t2, NULL); double time_step4 = (t2.tv_sec - t1.tv_sec) * 1000.0 + (t2.tv_usec - t1.tv_usec) / 1000.0; printf("transform_step4 runtime = %4.5f ms\n", time_step4); } #endif
GB_unop__identity_uint32_bool.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint32_bool) // op(A') function: GB (_unop_tran__identity_uint32_bool) // C type: uint32_t // A type: bool // cast: uint32_t cij = (uint32_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ uint32_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) \ uint32_t z = (uint32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint32_t z = (uint32_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_UINT32 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint32_bool) ( uint32_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] ; uint32_t z = (uint32_t) aij ; Cx [p] = z ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; bool aij = Ax [p] ; uint32_t z = (uint32_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_uint32_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
pt_to_pt_multiPingpong.c
/***************************************************************************** * * * Mixed-mode OpenMP/MPI MicroBenchmark Suite - Version 1.0 * * * * produced by * * * * Mark Bull, Jim Enright and Fiona Reid * * * * at * * * * Edinburgh Parallel Computing Centre * * * * email: markb@epcc.ed.ac.uk, fiona@epcc.ed.ac.uk * * * * * * Copyright 2012, The University of Edinburgh * * * * * * 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. * * * ****************************************************************************/ /*-----------------------------------------------------------*/ /* Contains the point-to-point multi-pingpong mixed mode */ /* OpenMP/MPI benchmarks. */ /* This includes: -masteronly multiPingpong */ /* -funnelled multiPingpong */ /* -multiple multiPingpong */ /*-----------------------------------------------------------*/ #include "pt_to_pt_multiPingpong.h" /*-----------------------------------------------------------*/ /* multiPingPong */ /* */ /* Driver subroutine for the multi-pingpong benchmark. */ /*-----------------------------------------------------------*/ int multiPingPong(int benchmarkType){ int dataSizeIter; int pongWorldRank; char pongProcName[MPI_MAX_PROCESSOR_NAME]; int balance; pingNode = 0; pongNode = 1; /* Check if there's a balance in num of MPI processes on pingNode and pongNode. */ balance = crossCommBalance(pingNode, pongNode); /* If not balanced.. */ if (balance == FALSE){ /* ..master prints error */ if (myMPIRank == 0){ printBalanceError(); } /* ..and all process exit function. */ return 1; } /* Exchange MPI_COMM_WORLD ranks for processes in same crossComm */ exchangeWorldRanks(pingNode, pongNode, &pongWorldRank); /* Processes on pongNode send processor name to pingNode procs. */ sendProcName(pingNode, pongNode, pongProcName); /* Print comm world ranks & processor name of processes * taking part in multi-pingpong benchmark. */ printMultiProcInfo(pingNode, pongWorldRank, pongProcName); /* Barrier to ensure that all procs have completed * printMultiProcInfo before prinring column headings. */ MPI_Barrier(comm); /* Master process then prints report column headings */ if (myMPIRank == 0){ printBenchHeader(); } /* Initialise repsToDo to defaultReps at start of benchmark */ repsToDo = defaultReps; dataSizeIter = minDataSize; /* initialise dataSizeIter to minDataSize */ /* Loop over data sizes */ while (dataSizeIter <= maxDataSize){ /* set sizeofBuffer */ sizeofBuffer = dataSizeIter * numThreads; /* Allocate space for the main data arrays */ allocateMultiPingpongData(sizeofBuffer); /* warm-up */ if (benchmarkType == MASTERONLY){ /* Masteronly warm-up */ masteronlyMultiPingpong(warmUpIters, dataSizeIter); } else if (benchmarkType == FUNNELLED){ /* Funnelled warm-up sweep */ funnelledMultiPingpong(warmUpIters, dataSizeIter); } else if (benchmarkType == MULTIPLE){ /* Multiple pingpong warm-up */ multipleMultiPingpong(warmUpIters, dataSizeIter); } /* Verification test for multi-pingpong */ testMultiPingpong(sizeofBuffer, dataSizeIter); /* Initialise benchmark */ benchComplete = FALSE; /* Keep executing benchmark until target time is reached */ while (benchComplete != TRUE){ /* MPI_Barrier to synchronise processes. Then start the timer. */ MPI_Barrier(comm); startTime = MPI_Wtime(); if (benchmarkType == MASTERONLY){ /* Execute masteronly multipingpong repsToDo times */ masteronlyMultiPingpong(repsToDo, dataSizeIter); } else if (benchmarkType == FUNNELLED){ /* Execute funnelled multipingpong */ funnelledMultiPingpong(repsToDo, dataSizeIter); } else if (benchmarkType == MULTIPLE){ multipleMultiPingpong(repsToDo, dataSizeIter); } /* Stop the timer..MPI_Barrier to synchronise processes * for more accurate timing. */ MPI_Barrier(comm); finishTime = MPI_Wtime(); totalTime = finishTime - startTime; /* Call repTimeCheck to check if target time is reached. */ if (myMPIRank==0){ benchComplete = repTimeCheck(totalTime, repsToDo); } /* Ensure all procs have the same value of benchComplete */ /* and repsToDo */ MPI_Bcast(&benchComplete, 1, MPI_INT, 0, comm); MPI_Bcast(&repsToDo, 1, MPI_INT, 0, comm); } /* End of loop to check if benchComplete is true */ /* Master process sets benchmark results */ if (myMPIRank == 0){ setReportParams(dataSizeIter, repsToDo, totalTime); printReport(); } /* Free the allocated space for the main data arrays */ freeMultiPingpongData(); /* Update dataSize before next iteration */ dataSizeIter = dataSizeIter * 2; } /* end loop over data sizes */ return 0; } /*-----------------------------------------------------------*/ /* masteronlyMultiPingpong */ /* */ /* All MPI processes in crossComm = pingNode sends a single */ /* fixed length message to the neighbouring process in */ /* crossComm = pongNode. */ /* The neighbouring processes then sends the message back */ /* to the first process. */ /*-----------------------------------------------------------*/ int masteronlyMultiPingpong(int totalReps, int dataSize){ int repIter, i; for (repIter = 1; repIter <= totalReps; repIter++){ /* Threads under each MPI process with * crossCommRank = pingNode write to pingSendBuf * array with a PARALLEL FOR directive. */ if (crossCommRank == pingNode){ #pragma omp parallel for default(none) \ private(i) \ shared(pingSendBuf,dataSize,sizeofBuffer,globalIDarray) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Each process with crossCommRank = pingNode sends * buffer to MPI process with rank = pongNode in crossComm. */ MPI_Send(pingSendBuf, sizeofBuffer, MPI_INT, pongNode, TAG, crossComm); /* The processes then wait for a message from pong process * and each thread reads its part of the received buffer. */ MPI_Recv(pongRecvBuf, sizeofBuffer, MPI_INT, pongNode, \ TAG, crossComm, &status); #pragma omp parallel for default(none) \ private(i) \ shared(pongRecvBuf,finalRecvBuf,dataSize,sizeofBuffer) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pongRecvBuf[i]; } } else if (crossCommRank == pongNode){ /* Each process with crossCommRank = pongNode receives * the message from the pingNode processes. */ MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, pingNode,\ TAG, crossComm, &status); /* Each thread copies its part of the received buffer * to pongSendBuf. */ #pragma omp parallel for default(none) \ private(i) \ shared(pongSendBuf,pingRecvBuf,dataSize,sizeofBuffer) \ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pongSendBuf[i] = pingRecvBuf[i]; } /* The processes now send pongSendBuf to processes * with crossCommRank = pingNode. */ MPI_Send(pongSendBuf, sizeofBuffer, MPI_INT, pingNode, \ TAG, crossComm); } } /* End repetitions loop */ return 0; } /*-----------------------------------------------------------*/ /* funnelledMultiPingpong */ /* */ /* All MPI processes in crossComm = pingNode sends a single */ /* fixed length message to the neighbouring process in */ /* crossComm = pongNode. */ /* The neighbouring processes then sends the message back */ /* to the first process. */ /* All communication takes place within the OpenMP parallel */ /* region for this benchmark. */ /*-----------------------------------------------------------*/ int funnelledMultiPingpong(int totalReps, int dataSize){ int repIter, i; /* Open the parallel region for threads */ #pragma omp parallel \ private(i,repIter) \ shared(pingNode,pongNode,pingSendBuf,pingRecvBuf) \ shared(pongSendBuf,pongRecvBuf,finalRecvBuf,sizeofBuffer) \ shared(dataSize,globalIDarray,crossComm,status) \ shared(totalReps,myMPIRank,crossCommRank) { /* loop totalRep times */ for (repIter = 1; repIter <= totalReps; repIter++){ /* All threads under each MPI process with * crossCommRank = pingNode write to pingSendBuf * array using a parallel for directive. */ if (crossCommRank == pingNode){ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Implicit barrier at end of omp for takes care of synchronisation */ /* Master thread under each pingNode process sends * buffer to corresponding MPI process in pongNode * using crossComm. */ #pragma omp master { MPI_Send(pingSendBuf, sizeofBuffer, MPI_INT, pongNode, TAG, crossComm); /* Master thread then waits for a message from the pong process. */ MPI_Recv(pongRecvBuf, sizeofBuffer, MPI_INT, pongNode, TAG, \ crossComm, &status); } /* Barrier needed to wait for master thread to complete MPI_Recv */ #pragma omp barrier /* Each thread then reads its part of the received buffer. */ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pongRecvBuf[i]; } } else if (crossCommRank == pongNode){ /* Master thread under each pongNode process receives * the message from the pingNode processes. */ #pragma omp master { MPI_Recv(pingRecvBuf, sizeofBuffer, MPI_INT, pingNode,\ TAG, crossComm, &status); } /* Barrier needed to wait on master thread */ #pragma omp barrier /* Each thread reads its part of the received buffer. */ #pragma omp for schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pongSendBuf[i] = pingRecvBuf[i]; } /* Implicit barrier at end of omp for */ /* Master threads send their pongSendBuf to processes * with crossCommRank = pingNode. */ #pragma omp master { MPI_Send(pongSendBuf, sizeofBuffer, MPI_INT, pingNode, TAG, crossComm); } } } /* End of repetitions loop. */ } /* End of parallel region */ return 0; } /*-----------------------------------------------------------*/ /* multipleMultiPingpong */ /* */ /* Multiple threads take place in the communication and */ /* computation. */ /* Each thread of all MPI processes in crossComm = pingNode */ /* sends a portion of the message to the neighbouring */ /* process in crossComm = pongNode. */ /* Each thread of the neighbouring processes then sends */ /* the message back to the first process. */ /*-----------------------------------------------------------*/ int multipleMultiPingpong(int totalReps, int dataSize){ int repIter, i; int lBound; /* Open parallel region for threads */ #pragma omp parallel \ private(i,repIter,status,lBound) \ shared(pingNode,pongNode,pingSendBuf,pingRecvBuf) \ shared(pongSendBuf,pongRecvBuf,finalRecvBuf,sizeofBuffer) \ shared(dataSize,globalIDarray,crossComm) \ shared(totalReps,myMPIRank,crossCommRank) { for (repIter=1; repIter<=totalReps; repIter++){ /* loop totalRep times */ if (crossCommRank == pingNode){ /* Calculate lower bound of data array for the thread */ lBound = (myThreadID * dataSize); /* All threads write to its part of the pingBuf * array using a parallel for directive. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pingSendBuf[i] = globalIDarray[myThreadID]; } /* Implicit barrier at end of for not needed for multiple */ /* Each thread under ping process sends dataSize items * to pongNode process in crossComm. * myThreadID is used as tag to ensure data goes to * correct place in buffer. */ MPI_Send(&pingSendBuf[lBound], dataSize, MPI_INT, pongNode, \ myThreadID, crossComm); /* Thread then waits for a message from pongNode. */ MPI_Recv(&pongRecvBuf[lBound], dataSize, MPI_INT, pongNode, \ myThreadID, crossComm, &status); /* Each thread reads its part of the received buffer. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ finalRecvBuf[i] = pongRecvBuf[i]; } } else if (crossCommRank == pongNode){ /* Calculate lower and upper bound of data array */ lBound = (myThreadID * dataSize); /* Each thread under pongRank receives a message from * the ping process. */ MPI_Recv(&pingRecvBuf[lBound], dataSize, MPI_INT, pingNode, \ myThreadID, crossComm, &status); /* Each thread now copies its part of the received buffer * to pongSendBuf. */ #pragma omp for nowait schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ pongSendBuf[i] = pingRecvBuf[i]; } /* Each thread now sends pongSendBuf to ping process. */ MPI_Send(&pongSendBuf[lBound], dataSize, MPI_INT, pingNode, \ myThreadID, crossComm); } } /* End repetitions loop */ } /* End parallel region */ return 0; } /*-----------------------------------------------------------*/ /* allocateMultiPingpongData */ /* */ /* Allocates space for the main data arrays. */ /* Size of each array is specified by subroutine argument. */ /*-----------------------------------------------------------*/ int allocateMultiPingpongData(int sizeofBuffer){ if (crossCommRank == pingNode){ /* allocate space for arrays that MPI processes * with crossCommRank = pingRank will use. */ pingSendBuf = (int *)malloc(sizeof(int) * sizeofBuffer); pongRecvBuf = (int *)malloc(sizeof(int) * sizeofBuffer); finalRecvBuf = (int *)malloc(sizeof(int) * sizeofBuffer); } else if (crossCommRank == pongNode){ /* allocate space for arrays that MPI processes * with crossCommRank = pongNode will use. */ pingRecvBuf = (int *)malloc(sizeof(int) * sizeofBuffer); pongSendBuf = (int *)malloc(sizeof(int) * sizeofBuffer); } return 0; } /*-----------------------------------------------------------*/ /* freeMultiPingpongData */ /* */ /* Deallocates the storage space for the main data arrays. */ /*-----------------------------------------------------------*/ int freeMultiPingpongData(){ if (crossCommRank == pingNode){ free(pingSendBuf); free(pongRecvBuf); free(finalRecvBuf); } else if (crossCommRank == pongNode){ free(pingRecvBuf); free(pongSendBuf); } return 0; } /*-----------------------------------------------------------*/ /* testMultiPingpong */ /* */ /* Verifies the the multi pingpong benchmark worked */ /* correctly. */ /*-----------------------------------------------------------*/ int testMultiPingpong(int sizeofBuffer, int dataSize){ int i; int testFlag, localTestFlag; /* Initialise localTestFlag to true */ localTestFlag = TRUE; /* All processes with crossCommRank = pingNode check * if multi-pingpong worked ok. */ if (crossCommRank == pingNode){ /* allocate space for testBuf */ testBuf = (int *)malloc(sizeof(int) * sizeofBuffer); /* Construct testBuf array with correct values. * These are the values that should be in finalRecvBuf. */ #pragma omp parallel for default(none) \ private(i) \ shared(testBuf,dataSize,sizeofBuffer,globalIDarray)\ schedule(static,dataSize) for (i=0; i<sizeofBuffer; i++){ testBuf[i] = globalIDarray[myThreadID]; } /* Compare each element of testBuf and finalRecvBuf */ for (i=0; i<sizeofBuffer; i++){ if (testBuf[i] != finalRecvBuf[i]){ localTestFlag = FALSE; } } /* Free space for testBuf */ free(testBuf); } /* Reduce localTestFlag to master */ MPI_Reduce(&localTestFlag, &testFlag, 1, MPI_INT,MPI_LAND, 0, comm); /* Master then sets testOutcome using reduceFlag */ if (myMPIRank == 0){ setTestOutcome(testFlag); } return 0; }
poisson_jacobi_omp.c
#include <math.h> #include <stdio.h> #include <string.h> int main() { int m = 512, n = 512; int iter = 0, iter_max = 1000; float err = 1.0, tol = 1.0e-5; const float pi = 2.0 * asinf(1.0); float y0[n]; float A[n][m], Anew[n][m]; // initialization memset(A, 0, n * m * sizeof(float)); // set boundary conditions #pragma omp parallel for for (int i = 0; i < m; i++) { A[0][i] = 0.0; A[n-1][i] = 0.0; } #pragma omp parallel for for (int j = 0; j < n; j++) { y0[j] = sinf(pi * j / (n-1)); A[j][0] = y0[j]; A[j][m-1] = y0[j]*expf(-pi); } while ( err > tol && iter < iter_max ) { err = 0.0; #pragma omp parallel for collapse(2) reduction (max:err) for( int j = 1; j < n-1; j++) { for(int i = 1; i < m-1; i++) { Anew[j][i] = 0.25 * (A[j][i+1] + A[j][i-1] + A[j-1][i] + A[j+1][i]); err = fmax(err, fabs(Anew[j][i] - A[j][i])); } } #pragma omp parallel for collapse(2) for( int j = 1; j < n-1; j++) { for( int i = 1; i < m-1; i++ ) { A[j][i] = Anew[j][i]; } } iter++; } printf("%e\n", err); printf("%d\n", iter); }
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-2020 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % 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=CastDoubleToLong(ceil(min.x-0.5)); geometry.y=CastDoubleToLong(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) \ 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) 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) 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; rotate_image=(Image *) NULL; rotate_view=(CacheView *) NULL; switch (rotations) { case 0: default: { rotate_image=CloneImage(image,0,0,MagickTrue,exception); break; } case 2: { rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); break; } case 1: case 3: { rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); break; } } if (rotate_image == (Image *) NULL) return((Image *) NULL); if (rotations == 0) return(rotate_image); /* 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) shared(status) \ magick_number_threads(image,rotate_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; 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) shared(status) \ magick_number_threads(image,rotate_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 atomic #endif progress++; 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) shared(status) \ magick_number_threads(image,rotate_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; 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) 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=CastDoubleToLong(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 atomic #endif progress++; 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) shared(progress,status) \ magick_number_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { 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; ssize_t step; 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=CastDoubleToLong(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 atomic #endif progress++; 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+CastDoubleToLong(floor(fabs(shear.x)* image->rows+0.5)); bounds.x=CastDoubleToLong(ceil((double) image->columns+((fabs(shear.x)* image->rows)-image->columns)/2.0-0.5)); bounds.y=CastDoubleToLong(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=fmod(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=CastDoubleToLong(floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5)); bounds.y=CastDoubleToLong(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); }
convolution_1x1.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. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); float32x4_t _p1 = vld1q_f32(r1); float32x4_t _p1n = vld1q_f32(r1+4); _outp = vfmaq_f32(_outp, _p1, _k1); _outpn = vfmaq_f32(_outpn, _p1n, _k1); float32x4_t _p2 = vld1q_f32(r2); float32x4_t _p2n = vld1q_f32(r2+4); _outp = vfmaq_f32(_outp, _p2, _k2); _outpn = vfmaq_f32(_outpn, _p2n, _k2); float32x4_t _p3 = vld1q_f32(r3); float32x4_t _p3n = vld1q_f32(r3+4); _outp = vfmaq_f32(_outp, _p3, _k3); _outpn = vfmaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; r1 += 8; r2 += 8; r3 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); float32x4x2_t _p1x2 = vld2q_f32(r1); float32x4_t _p1 = _p1x2.val[0]; float32x4x2_t _p1nx2 = vld2q_f32(r1+8); float32x4_t _p1n = _p1nx2.val[0]; _outp = vmlaq_f32(_outp, _p1, _k1); _outpn = vmlaq_f32(_outpn, _p1n, _k1); float32x4x2_t _p2x2 = vld2q_f32(r2); float32x4_t _p2 = _p2x2.val[0]; float32x4x2_t _p2nx2 = vld2q_f32(r2+8); float32x4_t _p2n = _p2nx2.val[0]; _outp = vmlaq_f32(_outp, _p2, _k2); _outpn = vmlaq_f32(_outpn, _p2n, _k2); float32x4x2_t _p3x2 = vld2q_f32(r3); float32x4_t _p3 = _p3x2.val[0]; float32x4x2_t _p3nx2 = vld2q_f32(r3+8); float32x4_t _p3n = _p3nx2.val[0]; _outp = vmlaq_f32(_outp, _p3, _k3); _outpn = vmlaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+8, _outpn); r0 += 16; r1 += 16; r2 += 16; r3 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } }
thscale_mpb.c
/* -*- Mode: C; c-basic-offset:4 ; indent-tabs-mode:nil ; -*- */ /* * See COPYRIGHT in top-level directory. */ #include <stdlib.h> #include <stdio.h> #include <omp.h> #include "queue/zm_mpbqueue.h" #define TEST_NELEMTS 64 #define NITER (1024*32) /*------------------------------------------------------------------------- * Function: run * * Purpose: Test the correctness of queue operations by counting the number * of dequeued elements to the expected number * * Return: Success: 0 * Failure: 1 *------------------------------------------------------------------------- */ static inline void run() { unsigned test_counter = 0; struct zm_mpbqueue queue; double t1, t2; int maxthreads = omp_get_max_threads(); printf("nbuckets,nthreads,throughput\n"); int nthreads, nbuckets; for (nbuckets = 1; nbuckets <= maxthreads; nbuckets *= 2) { for (nthreads = 2; nthreads <= maxthreads; nthreads ++) { zm_mpbqueue_init(&queue, nbuckets); int nelem_enq, nelem_deq; nelem_enq = TEST_NELEMTS/(nthreads-1); nelem_deq = (nthreads-1)*nelem_enq; t1 = omp_get_wtime(); #pragma omp parallel num_threads(nthreads) { int tid, producer_b, trg_bucket; size_t input = 1; tid = omp_get_thread_num(); producer_b = (tid != 0); trg_bucket = tid % nbuckets; int elem; for(int i = 0; i<NITER; i++) { if(producer_b) { /* producer */ for(elem=0; elem < nelem_enq; elem++) { zm_mpbqueue_enqueue(&queue, (void*) input, trg_bucket); } } else { /* consumer */ while(test_counter < nelem_deq) { void* elem = NULL; zm_mpbqueue_dequeue(&queue, (void**)&elem); if ((elem != NULL) && ((size_t)elem == 1)) { #pragma omp atomic test_counter++; } } } } } t2 = omp_get_wtime(); printf("%d,%d,%.3f\n", nbuckets, nthreads, (double)nelem_deq*NITER/(t2-t1)); } } } /* end run() */ int main(int argc, char **argv) { run(); } /* end main() */
pi_calculator.c
#include "pi_calculator.h" #include <math.h> #include <omp.h> #include <sys/types.h> #include <unistd.h> #include "math_utils.h" double calculatePi(int numberOfThreads, int numberOfPoints, int *numberOfPointsInsideCircle) { omp_set_num_threads(numberOfThreads); // Ponemos una seed aleatoria setSeed(getpid()); // Calculamos pi // Se va a usar solo un cuarto de circulo, por lo que el resultado final habra que // multiplicarlo por 4 int i = 0; int auxNumberOfPointsInsideCircle = 0; #pragma omp parallel for private(i) reduction(+ \ : auxNumberOfPointsInsideCircle) for (i = 0; i < numberOfPoints; i++) { // Generamos un punto entre 0 y 1 double x1 = generateRandomDouble(0.0, 1.0); double y1 = generateRandomDouble(0.0, 1.0); // Medimos la distancia con el centro (0,0) double distance = fabs(distanceBetweenPoints(x1, y1, 0, 0)); // Si la distancia es menor o igual que 1 es que esta dentro del circulo // de radio 1 if (distance <= 1) { auxNumberOfPointsInsideCircle++; } } *numberOfPointsInsideCircle = auxNumberOfPointsInsideCircle; // Ahora solo hay que calcular pi return ((double)auxNumberOfPointsInsideCircle / numberOfPoints) * 4; }
convolution_pack1to8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convolution_pack1to8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_packed, const Mat& bias_data, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const float* bias_data_ptr = bias_data; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { __m256 _sum = _mm256_setzero_ps(); if (bias_data_ptr) { _sum = _mm256_loadu_ps(bias_data_ptr + p * 8); } const float* kptr = weight_data_packed.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const float* sptr = m.row(i * stride_h) + j * stride_w; for (int k = 0; k < maxk; k++) { __m256 _val = _mm256_set1_ps(sptr[space_ofs[k]]); __m256 _w = _mm256_load_ps(kptr); _sum = _mm256_comp_fmadd_ps(_val, _w, _sum); kptr += 8; } } _sum = activation_avx(_sum, activation_type, activation_params); _mm256_store_ps(outptr + j * 8, _sum); } outptr += outw * 8; } } }
convolution_3x3.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 conv3x3s1_winograd23_transform_kernel_rvv(const Mat& kernel, Mat& kernel_tm2, int inch, int outch, const Option& opt) { Mat kernel_tm(4 * 4, inch, outch); // G const float ktm[4][3] = { {1.0f, 0.0f, 0.0f}, {1.0f / 2, 1.0f / 2, 1.0f / 2}, {1.0f / 2, -1.0f / 2, 1.0f / 2}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[4][3]; for (int i = 0; i < 4; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 4; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 4; i++) { kernel_tm0[j * 4 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 16-inch-outch // dst = inch-16-outch #if __riscv_vector kernel_tm2.create(8 * inch, 16, outch / 8 + (outch % 8) / 4 + outch % 4); #else kernel_tm2.create(2 * inch, 16, outch / 2 + outch % 2); #endif int q = 0; #if __riscv_vector for (; q + 7 < outch; q += 8) { Mat g0 = kernel_tm2.channel(q / 8); for (int k = 0; k < 16; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 8; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } for (; q + 3 < outch; q += 4) { Mat g0 = kernel_tm2.channel(q / 8 + (q % 8) / 4); for (int k = 0; k < 16; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 4; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } #else // __riscv_vector for (; q + 1 < outch; q += 2) { Mat g0 = kernel_tm2.channel(q / 2); for (int k = 0; k < 16; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 2; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } #endif // __riscv_vector for (; q < outch; q++) { #if __riscv_vector Mat g0 = kernel_tm2.channel(q / 8 + (q % 8) / 4 + q % 4); #else Mat g0 = kernel_tm2.channel(q / 2 + q % 2); #endif for (int k = 0; k < 16; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { const float* k00 = kernel_tm.channel(q).row(p); g00[0] = k00[k]; g00++; } } } } static void conv3x3s1_winograd23_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& bias, const Option& opt) { #if __riscv_vector const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); #endif int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 2n+2, winograd F(2,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 1) / 2 * 2; outh = (outh + 1) / 2 * 2; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); // BEGIN transform input Mat bottom_blob_tm; { int w_tiles = outw / 2; int h_tiles = outh / 2; int tiles = w_tiles * h_tiles; bottom_blob_tm.create(tiles, 16, inch, 4u, opt.workspace_allocator); conv3x3s1_winograd23_transform_input_rvv(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 2 * 4; int h_tm = outh / 2 * 4; const int tiles = h_tm / 4 * w_tm / 4; // permute Mat bottom_blob_tm2; #if __riscv_vector if (tiles >= packn) bottom_blob_tm2.create(packn * inch, tiles / packn + tiles % packn, 16, 4u, opt.workspace_allocator); #else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 16, 4u, opt.workspace_allocator); #endif else bottom_blob_tm2.create(1 * inch, tiles, 16, 4u, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 16; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __riscv_vector for (; i + (packn - 1) < tiles; i += packn) { float* tmpptr = tm2.row(i / packn); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { vse32_v_f32m1(tmpptr, vle32_v_f32m1(r0, vl), vl); r0 += bottom_blob_tm.cstep; tmpptr += packn; } } #else // __riscv_vector for (; i + 3 < tiles; i += 4) { float* tmpptr = tm2.row(i / 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { tmpptr[0] = r0[0]; tmpptr[1] = r0[1]; tmpptr[2] = r0[2]; tmpptr[3] = r0[3]; r0 += bottom_blob_tm.cstep; tmpptr += 4; } } #endif // __riscv_vector for (; i < tiles; i++) { #if __riscv_vector float* tmpptr = tm2.row(i / packn + i % packn); #else float* tmpptr = tm2.row(i / 4 + i % 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { tmpptr[0] = r0[0]; r0 += bottom_blob_tm.cstep; tmpptr += 1; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 16, outch, 4u, opt.workspace_allocator); #if __riscv_vector int nn_outch = outch >> 3; int remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); float* output4_tm = top_blob_tm.channel(p + 4); float* output5_tm = top_blob_tm.channel(p + 5); float* output6_tm = top_blob_tm.channel(p + 6); float* output7_tm = top_blob_tm.channel(p + 7); const Mat kernel0_tm = kernel_tm.channel(p / 8); for (int r = 0; r < 16; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum4 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum5 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum6 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum7 = vfmv_v_f_f32m1(0.f, vl); int j = 0; for (; j < nn; j++) { vfloat32m1_t _val = vle32_v_f32m1(r0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, k0[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, k0[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, k0[3], _val, vl); _sum4 = vfmacc_vf_f32m1(_sum4, k0[4], _val, vl); _sum5 = vfmacc_vf_f32m1(_sum5, k0[5], _val, vl); _sum6 = vfmacc_vf_f32m1(_sum6, k0[6], _val, vl); _sum7 = vfmacc_vf_f32m1(_sum7, k0[7], _val, vl); r0 += packn; k0 += 8; } vse32_v_f32m1(output0_tm, _sum0, vl); vse32_v_f32m1(output1_tm, _sum1, vl); vse32_v_f32m1(output2_tm, _sum2, vl); vse32_v_f32m1(output3_tm, _sum3, vl); vse32_v_f32m1(output4_tm, _sum4, vl); vse32_v_f32m1(output5_tm, _sum5, vl); vse32_v_f32m1(output6_tm, _sum6, vl); vse32_v_f32m1(output7_tm, _sum7, vl); output0_tm += packn; output1_tm += packn; output2_tm += packn; output3_tm += packn; output4_tm += packn; output5_tm += packn; output6_tm += packn; output7_tm += packn; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / packn + i % packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; float sum4 = 0.f; float sum5 = 0.f; float sum6 = 0.f; float sum7 = 0.f; int j = 0; for (; j < nn; j++) { sum0 += r0[0] * k0[0]; sum1 += r0[0] * k0[1]; sum2 += r0[0] * k0[2]; sum3 += r0[0] * k0[3]; sum4 += r0[0] * k0[4]; sum5 += r0[0] * k0[5]; sum6 += r0[0] * k0[6]; sum7 += r0[0] * k0[7]; r0 += 1; k0 += 8; } output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output4_tm[0] = sum4; output5_tm[0] = sum5; output6_tm[0] = sum6; output7_tm[0] = sum7; output0_tm++; output1_tm++; output2_tm++; output3_tm++; output4_tm++; output5_tm++; output6_tm++; output7_tm++; } } } nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); const Mat kernel0_tm = kernel_tm.channel(p / 8 + (p % 8) / 4); for (int r = 0; r < 16; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); int j = 0; for (; j < nn; j++) { vfloat32m1_t _val = vle32_v_f32m1(r0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, k0[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, k0[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, k0[3], _val, vl); r0 += packn; k0 += 4; } vse32_v_f32m1(output0_tm, _sum0, vl); vse32_v_f32m1(output1_tm, _sum1, vl); vse32_v_f32m1(output2_tm, _sum2, vl); vse32_v_f32m1(output3_tm, _sum3, vl); output0_tm += packn; output1_tm += packn; output2_tm += packn; output3_tm += packn; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / packn + i % packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; int j = 0; for (; j < nn; j++) { sum0 += r0[0] * k0[0]; sum1 += r0[0] * k0[1]; sum2 += r0[0] * k0[2]; sum3 += r0[0] * k0[3]; r0 += 1; k0 += 4; } output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output0_tm++; output1_tm++; output2_tm++; output3_tm++; } } } remain_outch_start += nn_outch << 2; #else int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); const Mat kernel0_tm = kernel_tm.channel(p / 2); for (int r = 0; r < 16; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum00 = 0.f; float sum01 = 0.f; float sum02 = 0.f; float sum03 = 0.f; float sum10 = 0.f; float sum11 = 0.f; float sum12 = 0.f; float sum13 = 0.f; for (int j = 0; j < nn; j++) { float w0 = k0[0]; float w1 = k0[1]; sum00 += r0[0] * w0; sum01 += r0[1] * w0; sum02 += r0[2] * w0; sum03 += r0[3] * w0; sum10 += r0[0] * w1; sum11 += r0[1] * w1; sum12 += r0[2] * w1; sum13 += r0[3] * w1; r0 += 4; k0 += 2; } output0_tm[0] = sum00; output0_tm[1] = sum01; output0_tm[2] = sum02; output0_tm[3] = sum03; output1_tm[0] = sum10; output1_tm[1] = sum11; output1_tm[2] = sum12; output1_tm[3] = sum13; output0_tm += 4; output1_tm += 4; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 4 + i % 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum00 = 0.f; float sum10 = 0.f; for (int j = 0; j < nn; j++) { float val0 = r0[0]; sum00 += val0 * k0[0]; sum10 += val0 * k0[1]; r0 += 1; k0 += 2; } output0_tm[0] = sum00; output1_tm[0] = sum10; output0_tm++; output1_tm++; } } } #endif #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); #if __riscv_vector const Mat kernel0_tm = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4); #else const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2); #endif for (int r = 0; r < 16; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __riscv_vector for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], vle32_v_f32m1(r0, vl), vl); r0 += packn; k0++; } vse32_v_f32m1(output0_tm, _sum0, vl); output0_tm += packn; } #else // __riscv_vector for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 16); __builtin_prefetch(k0 + 4); float w0 = k0[0]; sum0 += r0[0] * w0; sum1 += r0[1] * w0; sum2 += r0[2] * w0; sum3 += r0[3] * w0; r0 += 4; k0++; } output0_tm[0] = sum0; output0_tm[1] = sum1; output0_tm[2] = sum2; output0_tm[3] = sum3; output0_tm += 4; } #endif // __riscv_vector for (; i < tiles; i++) { #if __riscv_vector const float* r0 = bb2.row(i / packn + i % packn); #else const float* r0 = bb2.row(i / 4 + i % 4); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum = 0.f; for (int j = 0; j < nn; j++) { sum += r0[0] * k0[0]; r0 += 1; k0 += 1; } output0_tm[0] = sum; output0_tm += 1; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); } { conv3x3s1_winograd23_transform_output_rvv(top_blob_tm, top_blob_bordered, bias, opt); } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_winograd43_transform_kernel_rvv(const Mat& kernel, Mat& kernel_tm2, int inch, int outch, const Option& opt) { Mat kernel_tm(6 * 6, inch, outch); // G const float ktm[6][3] = { {1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6}, {1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = inch-36-outch #if __riscv_vector kernel_tm2.create(8 * inch, 36, outch / 8 + (outch % 8) / 4 + outch % 4); #else kernel_tm2.create(2 * inch, 36, outch / 2 + outch % 2); #endif int q = 0; #if __riscv_vector for (; q + 7 < outch; q += 8) { Mat g0 = kernel_tm2.channel(q / 8); for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 8; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } for (; q + 3 < outch; q += 4) { Mat g0 = kernel_tm2.channel(q / 8 + (q % 8) / 4); for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 4; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } #else // __riscv_vector for (; q + 1 < outch; q += 2) { Mat g0 = kernel_tm2.channel(q / 2); for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { for (int i = 0; i < 2; i++) { const float* k00 = kernel_tm.channel(q + i).row(p); g00[0] = k00[k]; g00++; } } } } #endif // __riscv_vector for (; q < outch; q++) { #if __riscv_vector Mat g0 = kernel_tm2.channel(q / 8 + (q % 8) / 4 + q % 4); #else Mat g0 = kernel_tm2.channel(q / 2 + q % 2); #endif for (int k = 0; k < 36; k++) { float* g00 = g0.row(k); for (int p = 0; p < inch; p++) { const float* k00 = kernel_tm.channel(q).row(p); g00[0] = k00[k]; g00++; } } } } static void conv3x3s1_winograd43_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& bias, const Option& opt) { #if __riscv_vector const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); #endif int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2, winograd F(4,3) Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; Option opt_b = opt; opt_b.blob_allocator = opt.workspace_allocator; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f, opt_b); // BEGIN transform input Mat bottom_blob_tm; { int w_tiles = outw / 4; int h_tiles = outh / 4; int tiles = w_tiles * h_tiles; bottom_blob_tm.create(tiles, 36, inch, 4u, opt.workspace_allocator); conv3x3s1_winograd43_transform_input_rvv(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute Mat bottom_blob_tm2; #if __riscv_vector if (tiles >= packn) bottom_blob_tm2.create(packn * inch, tiles / packn + tiles % packn, 36, 4u, opt.workspace_allocator); #else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + tiles % 4, 36, 4u, opt.workspace_allocator); #endif else bottom_blob_tm2.create(1 * inch, tiles, 36, 4u, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; #if __riscv_vector for (; i + (packn - 1) < tiles; i += packn) { float* tmpptr = tm2.row(i / packn); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { vse32_v_f32m1(tmpptr, vle32_v_f32m1(r0, vl), vl); r0 += bottom_blob_tm.cstep; tmpptr += packn; } } #else // __riscv_vector for (; i + 3 < tiles; i += 4) { float* tmpptr = tm2.row(i / 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { tmpptr[0] = r0[0]; tmpptr[1] = r0[1]; tmpptr[2] = r0[2]; tmpptr[3] = r0[3]; r0 += bottom_blob_tm.cstep; tmpptr += 4; } } #endif // __riscv_vector for (; i < tiles; i++) { #if __riscv_vector float* tmpptr = tm2.row(i / packn + i % packn); #else float* tmpptr = tm2.row(i / 4 + i % 4); #endif const float* r0 = bottom_blob_tm; r0 += (r * tiles + i); for (int q = 0; q < inch; q++) { tmpptr[0] = r0[0]; r0 += bottom_blob_tm.cstep; tmpptr += 1; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u, opt.workspace_allocator); #if __riscv_vector int nn_outch = outch >> 3; int remain_outch_start = nn_outch << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); float* output4_tm = top_blob_tm.channel(p + 4); float* output5_tm = top_blob_tm.channel(p + 5); float* output6_tm = top_blob_tm.channel(p + 6); float* output7_tm = top_blob_tm.channel(p + 7); const Mat kernel0_tm = kernel_tm.channel(p / 8); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum4 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum5 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum6 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum7 = vfmv_v_f_f32m1(0.f, vl); int j = 0; for (; j < nn; j++) { vfloat32m1_t _val = vle32_v_f32m1(r0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, k0[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, k0[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, k0[3], _val, vl); _sum4 = vfmacc_vf_f32m1(_sum4, k0[4], _val, vl); _sum5 = vfmacc_vf_f32m1(_sum5, k0[5], _val, vl); _sum6 = vfmacc_vf_f32m1(_sum6, k0[6], _val, vl); _sum7 = vfmacc_vf_f32m1(_sum7, k0[7], _val, vl); r0 += packn; k0 += 8; } vse32_v_f32m1(output0_tm, _sum0, vl); vse32_v_f32m1(output1_tm, _sum1, vl); vse32_v_f32m1(output2_tm, _sum2, vl); vse32_v_f32m1(output3_tm, _sum3, vl); vse32_v_f32m1(output4_tm, _sum4, vl); vse32_v_f32m1(output5_tm, _sum5, vl); vse32_v_f32m1(output6_tm, _sum6, vl); vse32_v_f32m1(output7_tm, _sum7, vl); output0_tm += packn; output1_tm += packn; output2_tm += packn; output3_tm += packn; output4_tm += packn; output5_tm += packn; output6_tm += packn; output7_tm += packn; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / packn + i % packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; float sum4 = 0.f; float sum5 = 0.f; float sum6 = 0.f; float sum7 = 0.f; int j = 0; for (; j < nn; j++) { sum0 += r0[0] * k0[0]; sum1 += r0[0] * k0[1]; sum2 += r0[0] * k0[2]; sum3 += r0[0] * k0[3]; sum4 += r0[0] * k0[4]; sum5 += r0[0] * k0[5]; sum6 += r0[0] * k0[6]; sum7 += r0[0] * k0[7]; r0 += 1; k0 += 8; } output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output4_tm[0] = sum4; output5_tm[0] = sum5; output6_tm[0] = sum6; output7_tm[0] = sum7; output0_tm++; output1_tm++; output2_tm++; output3_tm++; output4_tm++; output5_tm++; output6_tm++; output7_tm++; } } } nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = remain_outch_start + pp * 4; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); float* output2_tm = top_blob_tm.channel(p + 2); float* output3_tm = top_blob_tm.channel(p + 3); const Mat kernel0_tm = kernel_tm.channel(p / 8 + (p % 8) / 4); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum1 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum2 = vfmv_v_f_f32m1(0.f, vl); vfloat32m1_t _sum3 = vfmv_v_f_f32m1(0.f, vl); int j = 0; for (; j < nn; j++) { vfloat32m1_t _val = vle32_v_f32m1(r0, vl); _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], _val, vl); _sum1 = vfmacc_vf_f32m1(_sum1, k0[1], _val, vl); _sum2 = vfmacc_vf_f32m1(_sum2, k0[2], _val, vl); _sum3 = vfmacc_vf_f32m1(_sum3, k0[3], _val, vl); r0 += packn; k0 += 4; } vse32_v_f32m1(output0_tm, _sum0, vl); vse32_v_f32m1(output1_tm, _sum1, vl); vse32_v_f32m1(output2_tm, _sum2, vl); vse32_v_f32m1(output3_tm, _sum3, vl); output0_tm += packn; output1_tm += packn; output2_tm += packn; output3_tm += packn; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / packn + i % packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; int j = 0; for (; j < nn; j++) { sum0 += r0[0] * k0[0]; sum1 += r0[0] * k0[1]; sum2 += r0[0] * k0[2]; sum3 += r0[0] * k0[3]; r0 += 1; k0 += 4; } output0_tm[0] = sum0; output1_tm[0] = sum1; output2_tm[0] = sum2; output3_tm[0] = sum3; output0_tm++; output1_tm++; output2_tm++; output3_tm++; } } } remain_outch_start += nn_outch << 2; #else int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 2; float* output0_tm = top_blob_tm.channel(p); float* output1_tm = top_blob_tm.channel(p + 1); const Mat kernel0_tm = kernel_tm.channel(p / 2); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum00 = 0.f; float sum01 = 0.f; float sum02 = 0.f; float sum03 = 0.f; float sum10 = 0.f; float sum11 = 0.f; float sum12 = 0.f; float sum13 = 0.f; for (int j = 0; j < nn; j++) { float w0 = k0[0]; float w1 = k0[1]; sum00 += r0[0] * w0; sum01 += r0[1] * w0; sum02 += r0[2] * w0; sum03 += r0[3] * w0; sum10 += r0[0] * w1; sum11 += r0[1] * w1; sum12 += r0[2] * w1; sum13 += r0[3] * w1; r0 += 4; k0 += 2; } output0_tm[0] = sum00; output0_tm[1] = sum01; output0_tm[2] = sum02; output0_tm[3] = sum03; output1_tm[0] = sum10; output1_tm[1] = sum11; output1_tm[2] = sum12; output1_tm[3] = sum13; output0_tm += 4; output1_tm += 4; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 4 + i % 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum00 = 0.f; float sum10 = 0.f; for (int j = 0; j < nn; j++) { float val0 = r0[0]; sum00 += val0 * k0[0]; sum10 += val0 * k0[1]; r0 += 1; k0 += 2; } output0_tm[0] = sum00; output1_tm[0] = sum10; output0_tm++; output1_tm++; } } } #endif #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); #if __riscv_vector const Mat kernel0_tm = kernel_tm.channel(p / 8 + (p % 8) / 4 + p % 4); #else const Mat kernel0_tm = kernel_tm.channel(p / 2 + p % 2); #endif for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; #if __riscv_vector for (; i + (packn - 1) < tiles; i += packn) { const float* r0 = bb2.row(i / packn); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 vfloat32m1_t _sum0 = vfmv_v_f_f32m1(0.f, vl); for (int j = 0; j < nn; j++) { _sum0 = vfmacc_vf_f32m1(_sum0, k0[0], vle32_v_f32m1(r0, vl), vl); r0 += packn; k0++; } vse32_v_f32m1(output0_tm, _sum0, vl); output0_tm += packn; } #else // __riscv_vector for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 4); const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum0 = 0.f; float sum1 = 0.f; float sum2 = 0.f; float sum3 = 0.f; for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 16); __builtin_prefetch(k0 + 4); float w0 = k0[0]; sum0 += r0[0] * w0; sum1 += r0[1] * w0; sum2 += r0[2] * w0; sum3 += r0[3] * w0; r0 += 4; k0++; } output0_tm[0] = sum0; output0_tm[1] = sum1; output0_tm[2] = sum2; output0_tm[3] = sum3; output0_tm += 4; } #endif // __riscv_vector for (; i < tiles; i++) { #if __riscv_vector const float* r0 = bb2.row(i / packn + i % packn); #else const float* r0 = bb2.row(i / 4 + i % 4); #endif const float* k0 = kernel0_tm.row(r); int nn = inch; // inch always > 0 float sum = 0.f; for (int j = 0; j < nn; j++) { sum += r0[0] * k0[0]; r0 += 1; k0 += 1; } output0_tm[0] = sum; output0_tm += 1; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, 4u, opt.workspace_allocator); } { conv3x3s1_winograd43_transform_output_rvv(top_blob_tm, top_blob_bordered, bias, opt); } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
cg.20190406_parallel_block.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "globals.h" #include "randdp.h" #include "timers.h" #include <omp.h> //--------------------------------------------------------------------- #define CACHE_LINE_SIZE_PAD 128 #define INT_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(int) #define DOUBLE_PAD_SIZE CACHE_LINE_SIZE_PAD/sizeof(double) /* common / main_int_mem / */ static int colidx[NZ]; static int rowstr[NA+1]; static int iv[NA]; static int arow[NA]; static int acol[NAZ]; /* common / main_flt_mem / */ static double aelt[NAZ]; static double a[NZ]; static double x[NA+2]; static double z[NA+2]; static double p[NA+2]; static double q[NA+2]; static double r[NA+2]; /* common / partit_size / */ static int naa; static int nzz; static int firstrow; static int lastrow; static int firstcol; static int lastcol; /* common /urando/ */ static double amult; static double tran; /* common /timers/ */ static logical timeron; //--------------------------------------------------------------------- //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm); static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]); static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift); static void sprnvc(int n, int nz, int nn1, double v[], int iv[]); static int icnvrt(double x, int ipwr2); static void vecset(int n, double v[], int iv[], int *nzv, int i, double val); //--------------------------------------------------------------------- int main(int argc, char *argv[]) { omp_set_num_threads(omp_get_num_procs()); int i, j, k, it; double zeta; double rnorm; double norm_temp1, norm_temp2; double t, mflops, tmax; //char Class; logical verified; double zeta_verify_value, epsilon, err; char *t_names[T_last]; for (i = 0; i < T_last; i++) { timer_clear(i); } timer_start(T_init); firstrow = 0; lastrow = NA-1; firstcol = 0; lastcol = NA-1; zeta_verify_value = VALID_RESULT; printf("\nCG start...\n\n"); printf(" Size: %11d\n", NA); printf(" Iterations: %5d\n", NITER); printf("\n"); naa = NA; nzz = NZ; //--------------------------------------------------------------------- // Inialize random number generator //--------------------------------------------------------------------- tran = 314159265.0; amult = 1220703125.0; zeta = randlc(&tran, amult); //--------------------------------------------------------------------- // //--------------------------------------------------------------------- makea(naa, nzz, a, colidx, rowstr, firstrow, lastrow, firstcol, lastcol, arow, (int (*)[NONZER+1])(void*)acol, (double (*)[NONZER+1])(void*)aelt, iv); //--------------------------------------------------------------------- // Note: as a result of the above call to makea: // values of j used in indexing rowstr go from 0 --> lastrow-firstrow // values of colidx which are col indexes go from firstcol --> lastcol // So: // Shift the col index vals from actual (firstcol --> lastcol ) // to local, i.e., (0 --> lastcol-firstcol) //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(i,j,k) { #pragma omp for nowait for (j = 0; j < lastrow - firstrow + 1; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { colidx[k] = colidx[k] - firstcol; } } //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp for nowait for (i = 0; i < NA+1; i++) { x[i] = 1.0; } #pragma omp for nowait for (j = 0; j < lastcol - firstcol + 1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = 0.0; p[j] = 0.0; } } zeta = 0.0; //--------------------------------------------------------------------- //----> // Do one iteration untimed to init all code and data page tables //----> (then reinit, start timing, to niter its) //--------------------------------------------------------------------- for (it = 1; it <= 1; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j] * z[j]; norm_temp2 = norm_temp2 + z[j] * z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of do one iteration untimed //--------------------------------------------------------------------- // set starting vector to (1, 1, .... 1) //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(i) for (i = 0; i < NA+1; i++) { x[i] = 1.0; } zeta = 0.0; timer_stop(T_init); printf(" Initialization time = %15.3f seconds\n", timer_read(T_init)); timer_start(T_bench); //--------------------------------------------------------------------- //----> // Main Iteration for inverse power method //----> //--------------------------------------------------------------------- for (it = 1; it <= NITER; it++) { //--------------------------------------------------------------------- // The call to the conjugate gradient routine: //--------------------------------------------------------------------- if (timeron) timer_start(T_conj_grad); conj_grad(colidx, rowstr, x, z, a, p, q, r, &rnorm); if (timeron) timer_stop(T_conj_grad); //--------------------------------------------------------------------- // zeta = shift + 1/(x.z) // So, first: (x.z) // Also, find norm of z // So, first: (z.z) //--------------------------------------------------------------------- norm_temp1 = 0.0; norm_temp2 = 0.0; #pragma omp parallel for default(shared) private(j) reduction(+:norm_temp1,norm_temp2) for (j = 0; j < lastcol - firstcol + 1; j++) { norm_temp1 = norm_temp1 + x[j]*z[j]; norm_temp2 = norm_temp2 + z[j]*z[j]; } norm_temp2 = 1.0 / sqrt(norm_temp2); zeta = SHIFT + 1.0 / norm_temp1; if (it == 1) printf("\n iteration ||r|| zeta\n"); printf(" %5d %20.14E%20.13f\n", it, rnorm, zeta); //--------------------------------------------------------------------- // Normalize z to obtain x //--------------------------------------------------------------------- #pragma omp parallel for default(shared) private(j) for (j = 0; j < lastcol - firstcol + 1; j++) { x[j] = norm_temp2 * z[j]; } } // end of main iter inv pow meth timer_stop(T_bench); //--------------------------------------------------------------------- // End of timed section //--------------------------------------------------------------------- t = timer_read(T_bench); printf("\nComplete...\n"); epsilon = 1.0e-10; err = fabs(zeta - zeta_verify_value) / zeta_verify_value; if (err <= epsilon) { verified = true; printf(" VERIFICATION SUCCESSFUL\n"); printf(" Zeta is %20.13E\n", zeta); printf(" Error is %20.13E\n", err); } else { verified = false; printf(" VERIFICATION FAILED\n"); printf(" Zeta %20.13E\n", zeta); printf(" The correct zeta is %20.13E\n", zeta_verify_value); } printf("\n\nExecution time : %lf seconds\n\n", t); return 0; } //--------------------------------------------------------------------- // Floaging point arrays here are named as in spec discussion of // CG algorithm //--------------------------------------------------------------------- static void conj_grad(int colidx[], int rowstr[], double x[], double z[], double a[], double p[], double q[], double r[], double *rnorm) { int j, k; int cgit, cgitmax = 25; double d, sum, rho, rho0, alpha, beta; rho = 0.0; //--------------------------------------------------------------------- // Initialize the CG algorithm: //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < naa+1; j++) { q[j] = 0.0; z[j] = 0.0; r[j] = x[j]; p[j] = r[j]; } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp for reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j]*r[j]; } } //--------------------------------------------------------------------- //----> // The conj grad iteration loop //----> //--------------------------------------------------------------------- for (cgit = 1; cgit <= cgitmax; cgit++) { //--------------------------------------------------------------------- // q = A.p // The partition submatrix-vector multiply: use workspace w //--------------------------------------------------------------------- // // NOTE: this version of the multiply is actually (slightly: maybe %5) // faster on the sp2 on 16 nodes than is the unrolled-by-2 version // below. On the Cray t3d, the reverse is true, i.e., the // unrolled-by-two version is some 10% faster. // The unrolled-by-8 version below is significantly faster // on the Cray t3d - overall speed of code is 1.5 times faster. #pragma omp parallel default(shared) private(j, k, sum) { #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { sum = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { sum = sum + a[k]*p[colidx[k]]; } q[j] = sum; } } //--------------------------------------------------------------------- // Obtain p.q //--------------------------------------------------------------------- d = 0.0; #pragma omp parallel default(shared) private(j) { #pragma omp for reduction(+:d) for (j = 0; j < lastcol - firstcol + 1; j++) { d = d + p[j]*q[j]; } } //--------------------------------------------------------------------- // Obtain alpha = rho / (p.q) //--------------------------------------------------------------------- alpha = rho / d; //--------------------------------------------------------------------- // Save a temporary of rho //--------------------------------------------------------------------- rho0 = rho; //--------------------------------------------------------------------- // Obtain z = z + alpha*p // and r = r - alpha*q //--------------------------------------------------------------------- rho = 0.0; #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < lastcol - firstcol + 1; j++) { z[j] = z[j] + alpha*p[j]; r[j] = r[j] - alpha*q[j]; } } //--------------------------------------------------------------------- // rho = r.r // Now, obtain the norm of r: First, sum squares of r elements locally... //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for reduction(+:rho) for (j = 0; j < lastcol - firstcol + 1; j++) { rho = rho + r[j]*r[j]; } } //--------------------------------------------------------------------- // Obtain beta: //--------------------------------------------------------------------- beta = rho / rho0; //--------------------------------------------------------------------- // p = r + beta*p //--------------------------------------------------------------------- #pragma omp parallel default(shared) private(j) { #pragma omp for for (j = 0; j < lastcol - firstcol + 1; j++) { p[j] = r[j] + beta*p[j]; } } } // end of do cgit=1,cgitmax //--------------------------------------------------------------------- // Compute residual norm explicitly: ||r|| = ||x - A.z|| // First, form A.z // The partition submatrix-vector multiply //--------------------------------------------------------------------- /* for (j = 0; j < lastrow - firstrow + 1; j++) { printf("j = %d, colidx[%d] = %d, z[%d] = %lf\n", j, j, colidx[j], colidx[j], z[colidx[j]][0]); } */ double d_tmp; #pragma omp parallel default(shared) private(j, d, d_tmp) shared(sum) { sum = 0.0; #pragma omp for for (j = 0; j < lastrow - firstrow + 1; j++) { d = 0.0; for (k = rowstr[j]; k < rowstr[j+1]; k++) { d = d + a[k]*z[colidx[k]]; } r[j] = d; } //--------------------------------------------------------------------- // At this point, r contains A.z //--------------------------------------------------------------------- #pragma omp for reduction(+:sum) for (j = 0; j < lastcol-firstcol+1; j++) { d_tmp = x[j] - r[j]; sum = sum + d_tmp*d_tmp; } } *rnorm = sqrt(sum); } //--------------------------------------------------------------------- // generate the test problem for benchmark 6 // makea generates a sparse matrix with a // prescribed sparsity distribution // // parameter type usage // // input // // n i number of cols/rows of matrix // nz i nonzeros as declared array size // rcond r*8 condition number // shift r*8 main diagonal shift // // output // // a r*8 array for nonzeros // colidx i col indices // rowstr i row pointers // // workspace // // iv, arow, acol i // aelt r*8 //--------------------------------------------------------------------- static void makea(int n, int nz, double a[], int colidx[], int rowstr[], int firstrow, int lastrow, int firstcol, int lastcol, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int iv[]) { int iouter, ivelt, nzv, nn1; int ivc[NONZER+1]; double vc[NONZER+1]; //--------------------------------------------------------------------- // nonzer is approximately (int(sqrt(nnza /n))); //--------------------------------------------------------------------- //--------------------------------------------------------------------- // nn1 is the smallest power of two not less than n //--------------------------------------------------------------------- nn1 = 1; do { nn1 = 2 * nn1; } while (nn1 < n); //--------------------------------------------------------------------- // Generate nonzero positions and save for the use in sparse. //--------------------------------------------------------------------- for (iouter = 0; iouter < n; iouter++) { nzv = NONZER; sprnvc(n, nzv, nn1, vc, ivc); vecset(n, vc, ivc, &nzv, iouter+1, 0.5); arow[iouter] = nzv; for (ivelt = 0; ivelt < nzv; ivelt++) { acol[iouter][ivelt] = ivc[ivelt] - 1; aelt[iouter][ivelt] = vc[ivelt]; } } //--------------------------------------------------------------------- // ... make the sparse matrix from list of elements with duplicates // (iv is used as workspace) //--------------------------------------------------------------------- sparse(a, colidx, rowstr, n, nz, NONZER, arow, acol, aelt, firstrow, lastrow, iv, RCOND, SHIFT); } //--------------------------------------------------------------------- // rows range from firstrow to lastrow // the rowstr pointers are defined for nrows = lastrow-firstrow+1 values //--------------------------------------------------------------------- static void sparse(double a[], int colidx[], int rowstr[], int n, int nz, int nozer, int arow[], int acol[][NONZER+1], double aelt[][NONZER+1], int firstrow, int lastrow, int nzloc[], double rcond, double shift) { int nrows; //--------------------------------------------------- // generate a sparse matrix from a list of // [col, row, element] tri //--------------------------------------------------- int i, j, j1, j2, nza, k, kk, nzrow, jcol; double size, scale, ratio, va; logical cont40; //--------------------------------------------------------------------- // how many rows of result //--------------------------------------------------------------------- nrows = lastrow - firstrow + 1; //--------------------------------------------------------------------- // ...count the number of triples in each row //--------------------------------------------------------------------- for (j = 0; j < nrows+1; j++) { rowstr[j] = 0; } for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza] + 1; rowstr[j] = rowstr[j] + arow[i]; } } rowstr[0] = 0; for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] + rowstr[j-1]; } nza = rowstr[nrows] - 1; //--------------------------------------------------------------------- // ... rowstr(j) now is the location of the first nonzero // of row j of a //--------------------------------------------------------------------- if (nza > nz) { printf("Space for matrix elements exceeded in sparse\n"); printf("nza, nzmax = %d, %d\n", nza, nz); exit(EXIT_FAILURE); } //--------------------------------------------------------------------- // ... preload data pages //--------------------------------------------------------------------- for (j = 0; j < nrows; j++) { for (k = rowstr[j]; k < rowstr[j+1]; k++) { a[k] = 0.0; colidx[k] = -1; } nzloc[j] = 0; } //--------------------------------------------------------------------- // ... generate actual values by summing duplicates //--------------------------------------------------------------------- size = 1.0; ratio = pow(rcond, (1.0 / (double)(n))); for (i = 0; i < n; i++) { for (nza = 0; nza < arow[i]; nza++) { j = acol[i][nza]; scale = size * aelt[i][nza]; for (nzrow = 0; nzrow < arow[i]; nzrow++) { jcol = acol[i][nzrow]; va = aelt[i][nzrow] * scale; //-------------------------------------------------------------------- // ... add the identity * rcond to the generated matrix to bound // the smallest eigenvalue from below by rcond //-------------------------------------------------------------------- if (jcol == j && j == i) { va = va + rcond - shift; } cont40 = false; for (k = rowstr[j]; k < rowstr[j+1]; k++) { if (colidx[k] > jcol) { //---------------------------------------------------------------- // ... insert colidx here orderly //---------------------------------------------------------------- for (kk = rowstr[j+1]-2; kk >= k; kk--) { if (colidx[kk] > -1) { a[kk+1] = a[kk]; colidx[kk+1] = colidx[kk]; } } colidx[k] = jcol; a[k] = 0.0; cont40 = true; break; } else if (colidx[k] == -1) { colidx[k] = jcol; cont40 = true; break; } else if (colidx[k] == jcol) { //-------------------------------------------------------------- // ... mark the duplicated entry //-------------------------------------------------------------- nzloc[j] = nzloc[j] + 1; cont40 = true; break; } } if (cont40 == false) { printf("internal error in sparse: i=%d\n", i); exit(EXIT_FAILURE); } a[k] = a[k] + va; } } size = size * ratio; } //--------------------------------------------------------------------- // ... remove empty entries and generate final results //--------------------------------------------------------------------- for (j = 1; j < nrows; j++) { nzloc[j] = nzloc[j] + nzloc[j-1]; } for (j = 0; j < nrows; j++) { if (j > 0) { j1 = rowstr[j] - nzloc[j-1]; } else { j1 = 0; } j2 = rowstr[j+1] - nzloc[j]; nza = rowstr[j]; for (k = j1; k < j2; k++) { a[k] = a[nza]; colidx[k] = colidx[nza]; nza = nza + 1; } } for (j = 1; j < nrows+1; j++) { rowstr[j] = rowstr[j] - nzloc[j-1]; } nza = rowstr[nrows] - 1; } //--------------------------------------------------------------------- // generate a sparse n-vector (v, iv) // having nzv nonzeros // // mark(i) is set to 1 if position i is nonzero. // mark is all zero on entry and is reset to all zero before exit // this corrects a performance bug found by John G. Lewis, caused by // reinitialization of mark on every one of the n calls to sprnvc //--------------------------------------------------------------------- static void sprnvc(int n, int nz, int nn1, double v[], int iv[]) { int nzv, ii, i; double vecelt, vecloc; nzv = 0; while (nzv < nz) { vecelt = randlc(&tran, amult); //--------------------------------------------------------------------- // generate an integer between 1 and n in a portable manner //--------------------------------------------------------------------- vecloc = randlc(&tran, amult); i = icnvrt(vecloc, nn1) + 1; if (i > n) continue; //--------------------------------------------------------------------- // was this integer generated already? //--------------------------------------------------------------------- logical was_gen = false; for (ii = 0; ii < nzv; ii++) { if (iv[ii] == i) { was_gen = true; break; } } if (was_gen) continue; v[nzv] = vecelt; iv[nzv] = i; nzv = nzv + 1; } } //--------------------------------------------------------------------- // scale a double precision number x in (0,1) by a power of 2 and chop it //--------------------------------------------------------------------- static int icnvrt(double x, int ipwr2) { return (int)(ipwr2 * x); } //--------------------------------------------------------------------- // set ith element of sparse vector (v, iv) with // nzv nonzeros to val //--------------------------------------------------------------------- static void vecset(int n, double v[], int iv[], int *nzv, int i, double val) { int k; logical set; set = false; for (k = 0; k < *nzv; k++) { if (iv[k] == i) { v[k] = val; set = true; } } if (set == false) { v[*nzv] = val; iv[*nzv] = i; *nzv = *nzv + 1; } }
scatter_int_avx2.c
// create a list of 64 numbers, and only sum the even ones #include <stdio.h> #include <stdlib.h> #define N 32000 #define SCALE 8 int main() { srand(time(NULL)); int *numbers = malloc(sizeof(int)*N); int *result1 = malloc(sizeof(int)*N); int *result2 = malloc(sizeof(int)*N); int *mask = malloc(sizeof(int)*N); // Init the numbers for (int i = 0; i<N; i++) numbers[i] = rand() % 10; for (int i = 0; i<N; i++) { result1[i] = 0; result2[i] = 0; } for (int i = 0; i<N; i++) mask[i] = rand() % N; for (int i = 0; i<SCALE; i++) printf("%d ", numbers[i]); puts("\n---"); for (int i = 0; i<SCALE; i++) printf("%d ", mask[i]); puts("\n---"); puts("---------------------------------------------"); //Serial for (int i = 0; i<SCALE; i++) { result1[mask[i]] = numbers[mask[i]]; } #pragma omp simd simdlen(SCALE) for (int i = 0; i<SCALE; i++) { result2[mask[i]] = numbers[mask[i]]; } // print for (int i = 0; i<SCALE; i++) printf("%d ", result1[i]); puts("\n---"); for (int i = 0; i<SCALE; i++) printf("%d ", result2[i]); puts("\n---"); int errors = 0; for (int i = 0; i<SCALE; i++) { if (result1[i] != result2[i]) ++errors; } printf("Errors: %d\n", errors); //printf("Result1: %f | Result2: %f\n", result1, result2); return 0; }
es3.h
#ifndef es3_h #define es3_h #include <iostream> #include <omp.h> #define nt 8 #define ns 1000000000 #define PAD 8 using namespace std; //rendere le sum dinamiche void output(double pig, double time) { cout << "Time: " << time << endl << "PiGreco: " << pig << endl; } void ciclica(unsigned nmt) { int i, nthreads; double pig, sum[nt], step = 1.0/(double) ns; double start = omp_get_wtime(); omp_set_num_threads(nt); #pragma omp parallel num_threads(nmt) { int i, id, n; double x; id = omp_get_thread_num(); n = omp_get_num_threads(); if (id == 0) nthreads = n; for (i = id, sum[id] = 0.0; i < ns; i += n) { x = (i+0.5) * step; sum[id] += 4.0 / (1.0 + x * x); } } double end = omp_get_wtime(); for (i = 0, pig = 0.0; i < nthreads; i++) { pig += sum[i] * step; } output(pig, end - start); } void critica(unsigned nmt) { int i, nthreads; double pig, step = 1.0/(double) ns; double start = omp_get_wtime(); #pragma omp parallel num_threads(nmt) { int i, id, n; double x, sum; id = omp_get_thread_num(); n = omp_get_num_threads(); if (id == 0) nthreads = n; id = omp_get_num_threads(); for (i = id, sum = 0.0; i < ns; i += nthreads) { x = (i + 0.5) * step; sum += 4.0 / (1.0 + x * x); } #pragma omp critical pig += sum * step; } double end = omp_get_wtime(); output(pig, end - start); } void padding(unsigned nmt) { int i, nthreads; double pig, sum[nt][PAD], step = 1.0/(double) ns; double start = omp_get_wtime(); omp_set_num_threads(nt); #pragma omp parallel num_threads(nmt) { int i, id, n; double x; id = omp_get_thread_num(); n = omp_get_num_threads(); if (id == 0) nthreads = n; for (i = id, sum[id][0] = 0.0; i < ns; i += n) { x = (i+0.5) * step; sum[id][0] += 4.0 / (1.0 + x * x); } } double end = omp_get_wtime(); for (i = 0, pig = 0.0; i < nthreads; i++) { pig += sum[i][0] * step; } output(pig, end - start); } void reduction(unsigned nmt) { double area = 0.0, pig, x; int i, n; n = 100000; double start = omp_get_wtime(); #pragma omp parallel for private(x) reduction(+ : area) num_threads(nmt) for (i = 0; i < n; i++) { x = (i + 0.5) /n; area += 4.0 / (1.0 + x * x); } pig = area / n; double end = omp_get_wtime(); output(pig, end - start); } void monteCarlo(unsigned nmt) { long num_trials = 100000000, i, Ncirc = 0; double pig, x, y, r = 1.0; double start = omp_get_wtime(); #pragma omp parallel private(x, y) reduction(+ : Ncirc) num_threads(nmt) { unsigned int seed = (unsigned int) (omp_get_wtime()*10000.0*(double)omp_get_thread_num()/pi); #pragma omp for for (i = 0; i < num_trials; i++) { x = (double) rand_r(&seed) / RAND_MAX; y = (double) rand_r(&seed) / RAND_MAX; if (((x * x) + (y * y)) <= 1) { Ncirc++; } } } pig = 4.0 * ((double) Ncirc / (double) num_trials); double end = omp_get_wtime(); output(pig, end - start); } void es3() { cout << "Inserisci numero threads" << endl; unsigned nmt; cin >> nmt; cout << "Calcolo piGreco con distribuzione ciclica "; ciclica(nmt); cout << endl << "Calcolo piGreco con sezione critica "; critica(nmt); cout << endl << "Calcolo piGreco con padding "; padding(nmt); cout << endl; cout << endl << "Calcolo piGreco con reduction "; reduction(nmt); cout << endl << "Calcolo piGreco con Monte Carlo "; monteCarlo(nmt); cout << endl; } #endif
conv_kernel_rv64.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: ddzhao@openailab.com */ #include <stdint.h> #include <stdlib.h> #include <math.h> #include "conv_kernel_rv64.h" // #include "wino_conv_kernel_arm.h" // FIXME: add wino support // #include "wino_conv_kernel_1_arm.h" // FIXME: add wino support #define PER_OUT_CHAN 16 void sgemm_4x16_rv64(float* biases, float* input, float* kernel, long kernel_size, float* output, long output_xy, int activation, int layout); void sgemm_4x4_rv64(float* biases, float* input, float* kernel, long kernel_size, float* output, long output_xy, int activation, int layout); void im2col_fp32_1x1(float* input, int input_xy, float* col, int col_cnt, int input_chan); void im2col_fp32_3x3(float* input, int w, int h, int channel, float* cur_col, int stride); static void interleave_kernel(float* kernel, float* kernel_interleaved, int kernel_chan, int kernel_size) { int i, j, k; float* cur_kernel[PER_OUT_CHAN]; float* cur_kernel_interleaved = kernel_interleaved; // interleave PER_OUT_CHAN kernels for (i = 0; i + PER_OUT_CHAN - 1 < kernel_chan; i += PER_OUT_CHAN) { for (k = 0; k < PER_OUT_CHAN; k++) cur_kernel[k] = kernel + kernel_size * (i + k); for (j = 0; j < kernel_size; j++) { for (k = 0; k < PER_OUT_CHAN; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; } } for (; i < (kernel_chan & -4); i += 4) { for (k = 0; k < 4; k++) cur_kernel[k] = kernel + kernel_size * (i + k); for (j = 0; j < kernel_size; j++) { for (k = 0; k < 4; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; } } // last 4 kernel for (k = 0; k < 3; k++) cur_kernel[k] = kernel + kernel_size * (i + k); if ((kernel_chan & 0x3) == 3) { for (j = 0; j < kernel_size; j++) { for (k = 0; k < 3; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; *(cur_kernel_interleaved++) = 0.f; } } else if ((kernel_chan & 0x3) == 2) { for (j = 0; j < kernel_size; j++) { for (k = 0; k < 2; k++) *(cur_kernel_interleaved++) = cur_kernel[k][j]; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; } } else if ((kernel_chan & 0x3) == 1) { for (j = 0; j < kernel_size; j++) { *(cur_kernel_interleaved++) = cur_kernel[0][j]; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; *(cur_kernel_interleaved++) = 0.f; } } } /* kernel interleave */ static void interleave(struct tensor* filter, struct conv_priv_info* priv_info, struct conv_param* param) { int group = param->group; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size_algin = kernel_size * out_chan_align4; int kernel_size_group = kernel_size * out_chan; float* kernel = filter->data; float* interleave_buf = priv_info->interleave_buffer; for (int g = 0; g < group; g++) { float* cur_kernel = kernel + g * kernel_size_group; float* cur_interleave = interleave_buf + g * kernel_size_algin; interleave_kernel(cur_kernel, cur_interleave, out_chan, kernel_size); } } static void im2col(float* input, float* col, int in_c, int in_w, int in_h, int k_w, int k_h, int s_w, int s_h, int d_w, int d_h, int pad_w0, int pad_w1, int pad_h0, int pad_h1, int out_w, int out_h, int num_thread) { if (k_w == 1 && k_h == 1 && s_w == 1 && s_h == 1) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int out_xy = out_w * out_h; int col_end3 = out_xy & 3; #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < out_xy - 3; col_i += 4) { float* cur_col = col + col_i * kernel_size; float* cur_input = input + col_i; im2col_fp32_1x1(cur_input, in_xy, cur_col, 4, in_c); } int col_i = out_xy & -4; float* cur_col; // final 4 input if (col_end3) { cur_col = col + col_i * kernel_size; for (int col_j = 0; col_j < kernel_size; col_j++) { for (int i = 0; i < 4; i++) { if (i < col_end3) *cur_col++ = *(input + col_j * in_xy + col_i + i); else *cur_col++ = 0; } } } } else if (d_w == 1 && d_h == 1 && k_w == 3 && k_h == 3 && s_w == s_h) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int out_xy = out_w * out_h; int col_end3 = out_xy & 3; int is_pad0 = (pad_w0 == 0) && (pad_h0 == 0) && (pad_w1 == 0) && (pad_h1 == 0); #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < (out_xy & -4); col_i += 4) { float* cur_col = col + col_i * kernel_size; int imy0 = col_i / out_w; int imy3 = (col_i + 3) / out_w; int imx0 = col_i - imy0 * out_w; int imx3 = (col_i + 3) - imy3 * out_w; if ((imy0 == imy3) && (is_pad0 || (imy0 != 0 && imx0 != 0 && imy0 != (out_h - 1) && imx3 != (out_w - 1)))) { float* l0 = input + (imy0 * s_h - pad_h0) * in_w + (imx0 * s_w - pad_w0); { im2col_fp32_3x3(l0, in_w, in_h, in_c, cur_col, s_w); // add im2col 3x3 cur_col += 4 * kernel_size; } } else { int cnt_y[4] = {imy0, (col_i + 1) / out_w, (col_i + 2) / out_w, imy3}; int cnt_x[4] = {imx0, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, imx3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < 3; ky++) for (int kx = 0; kx < 3; kx++) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } // final 4 input int col_i = out_xy & -4; if (col_end3) { float* cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) { for (int ky = 0; ky < 3; ky++) { for (int kx = 0; kx < 3; kx++) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (i < col_end3 && imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } } } else { int out_xy = out_w * out_h; #pragma omp parallel for num_threads(num_thread) for (int col_i = 0; col_i < out_xy - 3; col_i += 4) { int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int col_end3 = out_xy & 3; float* cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < (k_h * d_h); ky += d_h) for (int kx = 0; kx < (k_w * d_w); kx += d_w) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } int col_i = out_xy & -4; float* cur_col; int kernel_size = k_w * k_h * in_c; int in_xy = in_w * in_h; int col_end3 = out_xy & 3; if (col_end3) { cur_col = col + col_i * kernel_size; int cnt_y[4] = {col_i / out_w, (col_i + 1) / out_w, (col_i + 2) / out_w, (col_i + 3) / out_w}; int cnt_x[4] = {col_i - cnt_y[0] * out_w, col_i - cnt_y[1] * out_w + 1, col_i - cnt_y[2] * out_w + 2, col_i - cnt_y[3] * out_w + 3}; int imx_start[4] = {cnt_x[0] * s_w - pad_w0, cnt_x[1] * s_w - pad_w0, cnt_x[2] * s_w - pad_w0, cnt_x[3] * s_w - pad_w0}; int imy_start[4] = {cnt_y[0] * s_h - pad_h0, cnt_y[1] * s_h - pad_h0, cnt_y[2] * s_h - pad_h0, cnt_y[3] * s_h - pad_h0}; for (int kch = 0; kch < in_c; kch++) for (int ky = 0; ky < (k_h * d_h); ky += d_h) for (int kx = 0; kx < (k_w * d_w); kx += d_w) { int imx[4] = {imx_start[0] + kx, imx_start[1] + kx, imx_start[2] + kx, imx_start[3] + kx}; int imy[4] = {imy_start[0] + ky, imy_start[1] + ky, imy_start[2] + ky, imy_start[3] + ky}; for (int i = 0; i < 4; i++) { if (i < col_end3 && imx[i] >= 0 && imx[i] < in_w && imy[i] >= 0 && imy[i] < in_h) *cur_col++ = *(input + in_xy * kch + in_w * imy[i] + imx[i]); else *cur_col++ = 0.f; } } } } } static void sgemm_set(float* col, float* kernel, float* biases, float* output, int kernel_size, int ch_start, int ch_end, int output_xy, int activation, int num_thread, int cpu_affinity) { int nn_outch = ch_end / PER_OUT_CHAN; int col_end3 = output_xy & 0x3; if (col_end3) { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * PER_OUT_CHAN; float* biasptr = biases ? (float*)(biases + p) : NULL; float* kernel_tmp = (float*)(kernel + p * kernel_size); float* output_tmp = (float*)(output + p * output_xy); int col_line = 0; for (col_line = 0; col_line + 3 < output_xy; col_line += 4) { float* col_tmp = (float*)(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, output_tmp + col_line, output_xy, activation, 0); // FIXME: replace with sgemm_4x16_rv64 } { float result[64]; float* col_tmp = (float*)(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, result, 4, activation, 0); // FIXME: replace with sgemm_4x16_rv64 for (int i = 0; i < 16; i++) { for (int j = 0; j < (col_end3); j++) *(output + (p + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } } else { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * PER_OUT_CHAN; float* biasptr = biases ? (float*)(biases + p) : NULL; float* kernel_tmp = (float*)(kernel + p * kernel_size); float* output_tmp = (float*)(output + p * output_xy); for (int col_line = 0; col_line + 3 < output_xy; col_line += 4) { float* col_tmp = (float*)(col + col_line * kernel_size); sgemm_4x16_rv64(biasptr, col_tmp, kernel_tmp, kernel_size, output_tmp + col_line, output_xy, activation, 0); // FIXME: replace with sgemm_4x16_rv64 } } } } static void sgemm4x4(float* col, float* kernel, float* biases, float* output, int kernel_size, int ch_start, int ch_end, int output_xy, int activation, int num_thread, int cpu_affinity) { float result[16]; int col_end3 = output_xy & 0x3; int kernel_end3 = ch_end & 0x3; #pragma omp parallel for num_threads(num_thread) private(result) for (int kernel_num = ch_start; kernel_num < ((ch_end & -4) - 3); kernel_num += 4) { float* cur_biases = NULL; float *cur_col, *cur_kernel, *cur_output; int col_line; if (biases) cur_biases = (float*)(biases + kernel_num); cur_kernel = (float*)(kernel + kernel_num * kernel_size); cur_output = (float*)(output + kernel_num * output_xy); for (col_line = 0; col_line < (output_xy & -4); col_line += 4) { cur_col = (float*)(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, cur_output + col_line, output_xy, activation, 0); } if (col_end3) { cur_col = (float*)(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < 4; i++) { for (int j = 0; j < (col_end3); j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } if (kernel_end3) { int kernel_num = (ch_end & -4); float* cur_biases = NULL; if (biases) cur_biases = (float*)(biases + kernel_num); float* cur_kernel = (float*)(kernel + kernel_num * kernel_size); #pragma omp parallel for num_threads(num_thread) private(result) for (int col_line = 0; col_line < (output_xy & -4); col_line += 4) { float* cur_col = (float*)(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < kernel_end3; i++) for (int j = 0; j < 4; j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } int col_line = output_xy & -4; if (col_end3) { float* cur_col = (float*)(col + col_line * kernel_size); sgemm_4x4_rv64(cur_biases, cur_col, cur_kernel, kernel_size, result, 4, activation, 0); for (int i = 0; i < (kernel_end3); i++) { for (int j = 0; j < (col_end3); j++) *(output + (kernel_num + i) * output_xy + col_line + j) = result[(i << 2) + j]; } } } } /* check the conv wheather need to be using winograd */ static int winograd_support(struct conv_param* param, int in_h, int in_w) { int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int output_chan = param->output_channel; int group = param->group; if (in_h < 7 && in_w < 7) return 0; if (in_h < 10 && in_w < 10 && output_chan < 16) return 0; if (group != 1 || kernel_h != 3 || kernel_w != 3) return 0; if (dilation_h != 1 || dilation_w != 1 || stride_h != 1 || stride_w != 1) return 0; return 1; } /* * get the memory size for im2col of input tensor */ int conv_hcl_get_shared_mem_size_rv64(struct tensor* input, struct tensor* output, struct conv_param* param) { int in_h = input->dims[2]; int in_w = input->dims[3]; int out_h = output->dims[2]; int out_w = output->dims[3]; int group = param->group; int input_chan = param->input_channel / group; int kernel_size = input_chan * param->kernel_h * param->kernel_w; int out_cstep = out_h * out_w; // channel cstep, output_h * output_w int elem_size = input->elem_size; // uint8/int8 is 1 byte, fp32 is 4 bytes out_cstep = (out_cstep + 3) / 4 * 4; int mem_size = elem_size * kernel_size * out_cstep + 128; return mem_size; } /* * get the memory size for im2col + sgemm of kernel tensor interleave */ static int get_private_mem_size(struct tensor* filter, struct conv_param* param) { int group = param->group; int out_chan = filter->dims[0] / group; int out_chan_align4 = (out_chan + 3) / 4 * 4; int kernel_size = filter->dims[1] * filter->dims[2] * filter->dims[3]; int mem_size = kernel_size * filter->elem_size * out_chan_align4 * group + 128; // caution return mem_size; } int conv_hcl_set_shared_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_mem = 1; priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; return 0; } int conv_hcl_set_shared_pack4_mem(struct conv_priv_info* priv_info, void* mem, int mem_size) { priv_info->external_im2col_pack4_mem = 0; priv_info->im2col_buffer_pack4 = NULL; priv_info->im2col_buffer_pack4_size = 0; return 0; } int conv_hcl_get_shared_pack4_mem_size(struct tensor* filter, struct tensor* output, struct conv_param* param) { return 0; } int conv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param) { int in_c = input_tensor->dims[1]; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; /* check winograd implement, only for conv3x3s1 */ // priv_info->winograd = winograd_support(param, in_h, in_w); // if (priv_info->winograd) // { // if(in_c >= 256) // // return wino_conv_hcl_prerun_1(input_tensor, filter_tensor, output_tensor, priv_info, param); // FIXME: add wino support // else // // return wino_conv_hcl_prerun(input_tensor, filter_tensor, output_tensor, priv_info, param); // FIXME: add wino support // } /* alloc mem of im2col */ if (!priv_info->external_im2col_mem) { int mem_size = conv_hcl_get_shared_mem_size_rv64(input_tensor, output_tensor, param); void* mem = sys_malloc(mem_size); priv_info->im2col_buffer = mem; priv_info->im2col_buffer_size = mem_size; } /* alloc mem of kernel interleave */ if (!priv_info->external_interleave_mem) { int mem_size = get_private_mem_size(filter_tensor, param); void* mem = sys_malloc(mem_size); priv_info->interleave_buffer = mem; priv_info->interleave_buffer_size = mem_size; } /* kernel interleave */ interleave(filter_tensor, priv_info, param); return 0; } int conv_hcl_postrun(struct conv_priv_info* priv_info) { // if (priv_info->winograd) // { // wino_conv_hcl_postrun(priv_info); // FIXME: add wino support // } if (!priv_info->external_interleave_mem && priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } if (!priv_info->external_im2col_mem && priv_info->im2col_buffer != NULL) { sys_free(priv_info->im2col_buffer); priv_info->im2col_buffer = NULL; } return 0; } int conv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* priv_info, struct conv_param* param, int num_thread, int cpu_affinity) { /* param */ int group = param->group; int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int stride_h = param->stride_h; int stride_w = param->stride_w; int dilation_h = param->dilation_h; int dilation_w = param->dilation_w; int pad_h0 = param->pad_h0; int pad_h1 = param->pad_h1; int pad_w0 = param->pad_w0; int pad_w1 = param->pad_w1; int act_type = param->activation; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_c * in_h * in_w; int kernel_size = in_c * kernel_h * kernel_w; int input_image_size = input_tensor->dims[1] * input_tensor->dims[2] * input_tensor->dims[3]; // if (priv_info->winograd) // { // if(in_c >= 256) // return wino_conv_hcl_run_1(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, num_thread, cpu_affinity); // FIXME: add wino support // else // return wino_conv_hcl_run(input_tensor, filter_tensor, bias_tensor, output_tensor, priv_info, param, num_thread, cpu_affinity); // FIXME: add wino support // } int out_c = output_tensor->dims[1] / group; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int out_c_align = ((out_c + 3) & -4); int output_image_size = output_tensor->dims[1] * output_tensor->dims[2] * output_tensor->dims[3]; /* buffer addr */ float* input_buf = (float*)input_tensor->data; float* output_buf = (float*)output_tensor->data; float* biases_buf = NULL; if (bias_tensor != NULL) biases_buf = (float*)bias_tensor->data; float* col_buf = (float*)priv_info->im2col_buffer; float* interleave_buf = (float*)priv_info->interleave_buffer; int sgemm_set_chan = out_c / PER_OUT_CHAN * PER_OUT_CHAN; int sgemm_set_remain = out_c % PER_OUT_CHAN; for (int n = 0; n < batch; n++) // batch size { for (int g = 0; g < group; g++) { /* im2col */ float* cur_input = input_buf + n * input_image_size + g * input_size; im2col(cur_input, col_buf, in_c, in_w, in_h, kernel_w, kernel_h, stride_w, stride_h, dilation_w, dilation_h, pad_w0, pad_w1, pad_h0, pad_h1, out_w, out_h, num_thread); /* gemm */ float* cur_kernel = interleave_buf + g * kernel_size * out_c_align; float* cur_output = output_buf + n * output_image_size + g * output_size; float* cur_bias = biases_buf ? (biases_buf + g * out_c) : NULL; sgemm_set(col_buf, cur_kernel, cur_bias, cur_output, kernel_size, 0, sgemm_set_chan, out_hw, act_type, num_thread, cpu_affinity); if (sgemm_set_remain) sgemm4x4(col_buf, cur_kernel, cur_bias, cur_output, kernel_size, sgemm_set_chan, out_c, out_hw, act_type, num_thread, cpu_affinity); } } return 0; }
bml_transpose_triangle_dense_typed.c
#include "../../macros.h" #include "../../typed.h" #include "../bml_allocate.h" #include "../bml_transpose_triangle.h" #include "../bml_types.h" #include "bml_allocate_dense.h" #include "bml_transpose_triangle_dense.h" #include "bml_types_dense.h" #include <complex.h> #include <stdlib.h> #include <string.h> #include <math.h> #ifdef _OPENMP #include <omp.h> #endif /** Transposes a triangle of a matrix in place. * * \ingroup transpose_triangle_group * * \param A The matrix for which the triangle should be transposed * \param triangle Which triangle to transpose ('u': upper, 'l': lower) */ void TYPED_FUNC( bml_transpose_triangle_dense) ( bml_matrix_dense_t * A, char triangle) { int N = A->N; REAL_T *A_matrix = A->matrix; switch (triangle) { case 'u': #pragma omp parallel for shared(N, A_matrix) for (int i = 0; i < N - 1; i++) { for (int j = i + 1; j < N; j++) { A_matrix[ROWMAJOR(j, i, N, N)] = A_matrix[ROWMAJOR(i, j, N, N)]; } } break; case 'l': #pragma omp parallel for shared(N, A_matrix) for (int i = 0; i < N - 1; i++) { for (int j = i + 1; j < N; j++) { A_matrix[ROWMAJOR(i, j, N, N)] = A_matrix[ROWMAJOR(j, i, N, N)]; } } break; } }
GB_binop__rdiv_uint64.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__rdiv_uint64 // A.*B function (eWiseMult): GB_AemultB__rdiv_uint64 // A*D function (colscale): GB_AxD__rdiv_uint64 // D*A function (rowscale): GB_DxB__rdiv_uint64 // C+=B function (dense accum): GB_Cdense_accumB__rdiv_uint64 // C+=b function (dense accum): GB_Cdense_accumb__rdiv_uint64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__rdiv_uint64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__rdiv_uint64 // C=scalar+B GB_bind1st__rdiv_uint64 // C=scalar+B' GB_bind1st_tran__rdiv_uint64 // C=A+scalar GB_bind2nd__rdiv_uint64 // C=A'+scalar GB_bind2nd_tran__rdiv_uint64 // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 64) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_IDIV_UNSIGNED (y, x, 64) ; // op is second #define GB_OP_IS_SECOND \ 0 // op is plus_fp32 or plus_fp64 #define GB_OP_IS_PLUS_REAL \ 0 // op is minus_fp32 or minus_fp64 #define GB_OP_IS_MINUS_REAL \ 0 // GB_cblas_*axpy gateway routine, if it exists for this operator and type: #define GB_CBLAS_AXPY \ (none) // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_RDIV || GxB_NO_UINT64 || GxB_NO_RDIV_UINT64) //------------------------------------------------------------------------------ // 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__rdiv_uint64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__rdiv_uint64 ( 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__rdiv_uint64 ( 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__rdiv_uint64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__rdiv_uint64 ( 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 uint64_t *GB_RESTRICT Cx = (uint64_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__rdiv_uint64 ( 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 uint64_t *GB_RESTRICT Cx = (uint64_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__rdiv_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__rdiv_uint64 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const 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__rdiv_uint64 ( 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 uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = GB_IDIV_UNSIGNED (bij, x, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__rdiv_uint64 ( 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 ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = Ax [p] ; Cx [p] = GB_IDIV_UNSIGNED (y, aij, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 64) ; \ } GrB_Info GB_bind1st_tran__rdiv_uint64 ( 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 \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 64) ; \ } GrB_Info GB_bind2nd_tran__rdiv_uint64 ( 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nco_s1d.c
/* $Header$ */ /* Purpose: NCO utilities for Sparse-1D (S1D) datasets */ /* Copyright (C) 2020--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ #include "nco_s1d.h" /* Sparse-1D datasets */ const char * /* O [sng] String describing sparse-type */ nco_s1d_sng /* [fnc] Convert sparse-1D type enum to string */ (const nco_s1d_typ_enm nco_s1d_typ) /* I [enm] Sparse-1D type enum */ { /* Purpose: Convert sparse-type enum to string */ switch(nco_s1d_typ){ case nco_s1d_clm: return "Sparse Column (cols1d) format"; case nco_s1d_grd: return "Sparse Gridcell (grid1d) format"; case nco_s1d_lnd: return "Sparse Landunit (land1d) format"; case nco_s1d_pft: return "Sparse PFT (pfts1d) format" ; default: nco_dfl_case_generic_err(); break; } /* !nco_s1d_typ_enm */ /* Some compilers: e.g., SGI cc, need return statement to end non-void functions */ return (char *)NULL; } /* !nco_s1d_sng() */ int /* O [rcd] Return code */ nco_s1d_unpack /* [fnc] Unpack sparse-1D CLM/ELM variables into full file */ (rgr_sct * const rgr, /* I/O [sct] Regridding structure */ trv_tbl_sct * const trv_tbl) /* I/O [sct] Traversal Table */ { /* Purpose: Read sparse CLM/ELM input file, inflate and write into output file */ /* Usage: ncks -D 1 -O -C --s1d ~/data/bm/elm_mali_bg_hst.nc ~/foo.nc ncks -D 1 -O -C --s1d -v cols1d_topoglc --hrz=${DATA}/bm/elm_mali_ig_hst.nc ${DATA}/bm/elm_mali_rst.nc ~/foo.nc ncks -D 1 -O -C --s1d -v GPP,pfts1d_wtgcell ~/beth_in.nc ~/foo.nc ncremap --dbg=1 --vrb=3 --devnull=No --nco='--dbg=1' -P elm -m ${DATA}/maps/map_ne30np4_to_fv128x256_aave.20160301.nc ~/foo.nc ~/foo_rgr.nc */ const char fnc_nm[]="nco_s1d_unpack()"; /* [sng] Function name */ char *fl_in; char *fl_out; char *fl_tpl; /* [sng] Template file (contains horizontal grid) */ char dmn_nm[NC_MAX_NAME]; /* [sng] Dimension name */ char *grd_nm_in=(char *)strdup("gridcell"); char *lnd_nm_in=(char *)strdup("landunit"); char *clm_nm_in=(char *)strdup("column"); char *pft_nm_in=(char *)strdup("pft"); char *mec_nm_out=(char *)strdup("mec"); int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int in_id; /* I [id] Input netCDF file ID */ int md_open; /* [enm] Mode flag for nc_open() call */ int out_id; /* I [id] Output netCDF file ID */ int rcd=NC_NOERR; int tpl_id; /* [id] Input netCDF file ID (for horizontal grid template) */ long int clm_idx; long int grd_idx_out; long int idx_out; //long int lat_idx; //long int lon_idx; long int pft_idx; int dmn_idx; /* [idx] Dimension index */ /* Initialize local copies of command-line values */ dfl_lvl=rgr->dfl_lvl; fl_in=rgr->fl_in; fl_out=rgr->fl_out; in_id=rgr->in_id; out_id=rgr->out_id; /* Search for horizontal grid */ char *bnd_nm_in=rgr->bnd_nm; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ char *col_nm_in=rgr->col_nm_in; /* [sng] Name to recognize as input horizontal spatial dimension on unstructured grid */ char *lat_nm_in=rgr->lat_nm_in; /* [sng] Name of input dimension to recognize as latitude */ char *lon_nm_in=rgr->lon_nm_in; /* [sng] Name of input dimension to recognize as longitude */ int dmn_id_bnd_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_col_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lat_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lon_in=NC_MIN_INT; /* [id] Dimension ID */ nco_bool FL_RTR_RMT_LCN; nco_bool flg_grd_1D=False; /* [flg] Unpacked data are on unstructured (1D) grid */ nco_bool flg_grd_2D=False; /* [flg] Unpacked data are on rectangular (2D) grid */ nco_bool flg_grd_dat=False; /* [flg] Use horizontal grid from required input data file */ nco_bool flg_grd_tpl=False; /* [flg] Use horizontal grid from optional horizontal grid template file */ nco_bool flg_nm_hst=False; /* [flg] Names in data file are as in history files ("ltype_"...) */ nco_bool flg_nm_rst=False; /* [flg] Names in data file are as in restart files ("ilun_"...) */ /* Does data file have unstructured grid? MB: Routine must handle two semantically distinct meanings of "column": 1. The horizontal dimension in an unstructured grid 2. A fraction of a landunit, which is a fraction of a CTSM/ELM gridcell In particular, a column is a fraction of a vegetated, urban, glacier, or crop landunit This routine distinguishes these meanings by abbreviating (1) as "col" and (2) as "clm" This usage maintains the precedent that "col" is the horizontal unstructured dimension in nco_rgr.c It is necessary though unintuitive that "cols1d" variable metadata will use the "clm" abbreviation */ if(col_nm_in && (rcd=nco_inq_dimid_flg(in_id,col_nm_in,&dmn_id_col_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"lndgrid",&dmn_id_col_in)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */ if(dmn_id_col_in != NC_MIN_INT) flg_grd_1D=True; /* Does data file have RLL grid? */ if(!flg_grd_1D){ if(lat_nm_in && (rcd=nco_inq_dimid_flg(in_id,lat_nm_in,&dmn_id_lat_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"latitude",&dmn_id_lat_in)) == NC_NOERR) lat_nm_in=strdup("lndgrid"); /* CF */ if(lon_nm_in && (rcd=nco_inq_dimid_flg(in_id,lon_nm_in,&dmn_id_lon_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(in_id,"longitude",&dmn_id_lon_in)) == NC_NOERR) lon_nm_in=strdup("lndgrid"); /* CF */ } /* !flg_grd_1D */ if(dmn_id_lat_in != NC_MIN_INT && dmn_id_lon_in != NC_MIN_INT) flg_grd_2D=True; /* Set where to obtain horizontal grid */ if(flg_grd_1D || flg_grd_2D) flg_grd_dat=True; else flg_grd_tpl=True; if(flg_grd_tpl && !rgr->fl_hrz){ (void)fprintf(stderr,"%s: ERROR %s did not locate horizontal grid in input data file and no optional horizontal gridfile was provided.\nHINT: Use option --hrz to specify file with horizontal grid used by input data.\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !flg_grd_tpl */ /* Open grid template file iff necessary */ if(flg_grd_tpl && rgr->fl_hrz){ char *fl_pth_lcl=NULL; nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_OPEN=rgr->flg_uio; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ /* Duplicate (because nco_fl_mk_lcl() free()'s its fl_in) */ fl_tpl=(char *)strdup(rgr->fl_hrz); /* Make sure file is on local system and is readable or die trying */ fl_tpl=nco_fl_mk_lcl(fl_tpl,fl_pth_lcl,HPSS_TRY,&FL_RTR_RMT_LCN); /* Open file using appropriate buffer size hints and verbosity */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; rcd+=nco_fl_open(fl_tpl,md_open,&bfr_sz_hnt,&tpl_id); /* Same logic used to search for grid in data file and to search for grid in template file... Does template file have unstructured grid? */ if(col_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,col_nm_in,&dmn_id_col_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(tpl_id,"lndgrid",&dmn_id_col_in)) == NC_NOERR) col_nm_in=strdup("lndgrid"); /* CLM */ if(dmn_id_col_in != NC_MIN_INT) flg_grd_1D=True; /* Does template file have RLL grid? */ if(!flg_grd_1D){ if(lat_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,lat_nm_in,&dmn_id_lat_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(tpl_id,"latitude",&dmn_id_lat_in)) == NC_NOERR) lat_nm_in=strdup("lndgrid"); /* CF */ if(lon_nm_in && (rcd=nco_inq_dimid_flg(tpl_id,lon_nm_in,&dmn_id_lon_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(tpl_id,"longitude",&dmn_id_lon_in)) == NC_NOERR) lon_nm_in=strdup("lndgrid"); /* CF */ } /* !flg_grd_1D */ if(dmn_id_lat_in != NC_MIN_INT && dmn_id_lon_in != NC_MIN_INT) flg_grd_2D=True; /* Set where to obtain horizontal grid */ if(!flg_grd_1D && !flg_grd_2D){ (void)fprintf(stderr,"%s: ERROR %s did not locate horizontal grid in input data file %s or in template file %s.\nHINT: One of those files must contain the grid dimensions and coordinates used by the packed data in the input data file.\n",nco_prg_nm_get(),fnc_nm,fl_in,fl_tpl); nco_exit(EXIT_FAILURE); } /* !flg_grd_1D */ } /* !flg_grd_tpl */ int cols1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of column */ int cols1d_ixy_id=NC_MIN_INT; /* [id] Column 2D longitude index */ int cols1d_jxy_id=NC_MIN_INT; /* [id] Column 2D latitude index */ int cols1d_lat_id=NC_MIN_INT; /* [id] Column latitude */ int cols1d_lon_id=NC_MIN_INT; /* [id] Column longitude */ int cols1d_ityp_id=NC_MIN_INT; /* [id] Column type */ int cols1d_ityplun_id=NC_MIN_INT; /* [id] Column landunit type */ int grid1d_ixy_id=NC_MIN_INT; /* [id] Gridcell 2D longitude index */ int grid1d_jxy_id=NC_MIN_INT; /* [id] Gridcell 2D latitude index */ int grid1d_lat_id=NC_MIN_INT; /* [id] Gridcell latitude */ int grid1d_lon_id=NC_MIN_INT; /* [id] Gridcell longitude */ int land1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of landunit */ int land1d_ixy_id=NC_MIN_INT; /* [id] Landunit 2D longitude index */ int land1d_jxy_id=NC_MIN_INT; /* [id] Landunit 2D latitude index */ int land1d_lat_id=NC_MIN_INT; /* [id] Landunit latitude */ int land1d_lon_id=NC_MIN_INT; /* [id] Landunit longitude */ int pfts1d_column_index_id=NC_MIN_INT; /* [id] Column index of PFT */ int pfts1d_gridcell_index_id=NC_MIN_INT; /* [id] Gridcell index of PFT */ int pfts1d_ityp_veg_id=NC_MIN_INT; /* [id] PFT vegetation type */ int pfts1d_ityplun_id=NC_MIN_INT; /* [id] PFT landunit type */ int pfts1d_ixy_id=NC_MIN_INT; /* [id] PFT 2D longitude index */ int pfts1d_jxy_id=NC_MIN_INT; /* [id] PFT 2D latitude index */ int pfts1d_lat_id=NC_MIN_INT; /* [id] PFT latitude */ int pfts1d_lon_id=NC_MIN_INT; /* [id] PFT longitude */ //int pfts1d_wtgcell_id=NC_MIN_INT; /* [id] PFT weight relative to corresponding gridcell */ int dmn_id_clm_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_grd_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lnd_in=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_pft_in=NC_MIN_INT; /* [id] Dimension ID */ nco_bool flg_s1d_clm=False; /* [flg] Dataset contains sparse variables for columns */ nco_bool flg_s1d_grd=False; /* [flg] Dataset contains sparse variables for gridcells */ nco_bool flg_s1d_lnd=False; /* [flg] Dataset contains sparse variables for landunits */ nco_bool flg_s1d_pft=False; /* [flg] Dataset contains sparse variables for PFTs */ rcd=nco_inq_att_flg(in_id,NC_GLOBAL,"ilun_vegetated_or_bare_soil",(nc_type *)NULL,(long *)NULL); if(rcd == NC_NOERR) flg_nm_rst=True; rcd=nco_inq_att_flg(in_id,NC_GLOBAL,"ltype_vegetated_or_bare_soil",(nc_type *)NULL,(long *)NULL); if(rcd == NC_NOERR) flg_nm_hst=True; assert(!(flg_nm_hst && flg_nm_rst)); if(!flg_nm_hst && !flg_nm_rst){ (void)fprintf(stderr,"%s: ERROR %s reports input data file lacks expected global attributes\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !flg_nm_hst */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stderr,"%s: INFO %s will assume input attributes and variables use CLM/ELM %s naming conventions like %s\n",nco_prg_nm_get(),fnc_nm,flg_nm_hst ? "history file" : "restart file",flg_nm_hst ? "\"ltype_...\"" : "\"ilun_...\""); rcd=nco_inq_varid_flg(in_id,"cols1d_lat",&cols1d_lat_id); if(cols1d_lat_id != NC_MIN_INT) flg_s1d_clm=True; if(flg_s1d_clm){ rcd=nco_inq_varid(in_id,"cols1d_ixy",&cols1d_ixy_id); rcd=nco_inq_varid(in_id,"cols1d_jxy",&cols1d_jxy_id); rcd=nco_inq_varid(in_id,"cols1d_lon",&cols1d_lon_id); rcd=nco_inq_varid_flg(in_id,"cols1d_gridcell_index",&cols1d_gridcell_index_id); /* ELM/MALI restart */ rcd=nco_inq_varid_flg(in_id,"cols1d_ityp",&cols1d_ityp_id); /* ELM/MALI restart */ if(flg_nm_hst) rcd=nco_inq_varid(in_id,"cols1d_itype_lunit",&cols1d_ityplun_id); else rcd=nco_inq_varid(in_id,"cols1d_ityplun",&cols1d_ityplun_id); } /* !flg_s1d_clm */ rcd=nco_inq_varid_flg(in_id,"grid1d_lat",&grid1d_lat_id); if(grid1d_lat_id != NC_MIN_INT) flg_s1d_grd=True; if(flg_s1d_grd){ rcd=nco_inq_varid(in_id,"grid1d_ixy",&grid1d_ixy_id); rcd=nco_inq_varid(in_id,"grid1d_jxy",&grid1d_jxy_id); rcd=nco_inq_varid(in_id,"grid1d_lon",&grid1d_lon_id); } /* !flg_s1d_grd */ rcd=nco_inq_varid_flg(in_id,"land1d_lat",&land1d_lat_id); if(land1d_lat_id != NC_MIN_INT) flg_s1d_lnd=True; if(flg_s1d_lnd){ rcd=nco_inq_varid_flg(in_id,"land1d_gridcell_index",&land1d_gridcell_index_id); rcd=nco_inq_varid(in_id,"land1d_ixy",&land1d_ixy_id); rcd=nco_inq_varid(in_id,"land1d_jxy",&land1d_jxy_id); rcd=nco_inq_varid(in_id,"land1d_lon",&land1d_lon_id); } /* !flg_s1d_lnd */ rcd=nco_inq_varid_flg(in_id,"pfts1d_lat",&pfts1d_lat_id); if(pfts1d_lat_id != NC_MIN_INT) flg_s1d_pft=True; if(flg_s1d_pft){ rcd=nco_inq_varid(in_id,"pfts1d_ixy",&pfts1d_ixy_id); rcd=nco_inq_varid(in_id,"pfts1d_jxy",&pfts1d_jxy_id); rcd=nco_inq_varid(in_id,"pfts1d_lon",&pfts1d_lon_id); rcd=nco_inq_varid_flg(in_id,"pfts1d_column_index",&pfts1d_column_index_id); rcd=nco_inq_varid_flg(in_id,"pfts1d_gridcell_index",&pfts1d_gridcell_index_id); //if(flg_nm_hst) rcd=nco_inq_varid(in_id,"pfts1d_wtgcell",&pfts1d_wtgcell_id); else rcd=nco_inq_varid(in_id,"pfts1d_wtxy",&pfts1d_wtgcell_id); if(flg_nm_hst) rcd=nco_inq_varid(in_id,"pfts1d_itype_lunit",&pfts1d_ityplun_id); else rcd=nco_inq_varid(in_id,"pfts1d_ityplun",&pfts1d_ityplun_id); if(flg_nm_hst) rcd=nco_inq_varid(in_id,"pfts1d_itype_veg",&pfts1d_ityp_veg_id); else rcd=nco_inq_varid(in_id,"pfts1d_itypveg",&pfts1d_ityp_veg_id); } /* !flg_s1d_pft */ if(!(flg_s1d_clm || flg_s1d_lnd || flg_s1d_pft)){ (void)fprintf(stderr,"%s: ERROR %s does not detect any of the key variables (currently cols1d_lat, land1d_lat, pfts1d_lat) used to indicate presence of sparse-packed (S1D) variables\nHINT: Be sure the target dataset (file) contains S1D variables---not all CLM/ELM history (as opposed to restart) files do\n",nco_prg_nm_get(),fnc_nm); nco_exit(EXIT_FAILURE); } /* !flg_s1d_clm... */ if(flg_s1d_clm) rcd=nco_inq_dimid(in_id,clm_nm_in,&dmn_id_clm_in); if(flg_s1d_grd) rcd=nco_inq_dimid(in_id,grd_nm_in,&dmn_id_grd_in); if(flg_s1d_lnd) rcd=nco_inq_dimid(in_id,lnd_nm_in,&dmn_id_lnd_in); if(flg_s1d_pft) rcd=nco_inq_dimid(in_id,pft_nm_in,&dmn_id_pft_in); if(nco_dbg_lvl_get() >= nco_dbg_std){ (void)fprintf(stderr,"%s: INFO %s necessary information to unpack cols1d variables\n",nco_prg_nm_get(),flg_s1d_clm ? "Found all" : "Could not find"); (void)fprintf(stderr,"%s: INFO %s necessary information to unpack land1d variables\n",nco_prg_nm_get(),flg_s1d_lnd ? "Found all" : "Could not find"); (void)fprintf(stderr,"%s: INFO %s necessary information to unpack pfts1d variables\n",nco_prg_nm_get(),flg_s1d_pft ? "Found all" : "Could not find"); } /* !dbg */ /* Collect other information from data and template files */ int dmn_nbr_in; /* [nbr] Number of dimensions in input file */ int dmn_nbr_out; /* [nbr] Number of dimensions in output file */ int var_nbr; /* [nbr] Number of variables in file */ rcd=nco_inq(in_id,&dmn_nbr_in,&var_nbr,(int *)NULL,(int *)NULL); const unsigned int trv_nbr=trv_tbl->nbr; /* [idx] Number of traversal table entries */ int var_cpy_nbr=0; /* [nbr] Number of copied variables */ int var_rgr_nbr=0; /* [nbr] Number of unpacked variables */ int var_xcl_nbr=0; /* [nbr] Number of deleted variables */ int var_crt_nbr=0; /* [nbr] Number of created variables */ //long idx; /* [idx] Generic index */ unsigned int idx_tbl; /* [idx] Counter for traversal table */ char *dmn_nm_cp; /* [sng] Dimension name as char * to reduce indirection */ nco_bool has_clm; /* [flg] Contains column dimension */ nco_bool has_grd; /* [flg] Contains gridcell dimension */ nco_bool has_lnd; /* [flg] Contains landunit dimension */ nco_bool has_pft; /* [flg] Contains PFT dimension */ nco_bool need_clm=False; /* [flg] At least one variable to unpack needs column dimension */ nco_bool need_grd=False; /* [flg] At least one variable to unpack needs gridcell dimension */ nco_bool need_lnd=False; /* [flg] At least one variable to unpack needs landunit dimension */ // nco_bool need_mec=False; /* [flg] At least one variable to unpack needs MEC dimension */ nco_bool need_pft=False; /* [flg] At least one variable to unpack needs PFT dimension */ trv_sct trv; /* [sct] Traversal table object structure to reduce indirection */ /* Define unpacking flag for each variable */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ dmn_nbr_in=trv_tbl->lst[idx_tbl].nbr_dmn; has_clm=has_grd=has_lnd=has_pft=False; for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ /* Pre-determine flags necessary during next loop */ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; if(!has_clm && clm_nm_in) has_clm=!strcmp(dmn_nm_cp,clm_nm_in); if(!has_grd && grd_nm_in) has_grd=!strcmp(dmn_nm_cp,grd_nm_in); if(!has_lnd && lnd_nm_in) has_lnd=!strcmp(dmn_nm_cp,lnd_nm_in); if(!has_pft && pft_nm_in) has_pft=!strcmp(dmn_nm_cp,pft_nm_in); } /* !dmn_idx */ /* Unpack variables that contain a sparse-1D dimension */ if(has_clm || has_grd || has_lnd || has_pft){ trv_tbl->lst[idx_tbl].flg_rgr=True; var_rgr_nbr++; if(has_clm) need_clm=True; if(has_grd) need_grd=True; if(has_lnd) need_lnd=True; if(has_pft) need_pft=True; } /* endif */ /* Copy all variables that are not regridded or omitted */ if(!trv_tbl->lst[idx_tbl].flg_rgr) var_cpy_nbr++; } /* end nco_obj_typ_var */ } /* end idx_tbl */ if(!var_rgr_nbr) (void)fprintf(stdout,"%s: WARNING %s reports no variables fit unpacking criteria. The sparse data unpacker expects at least one variable to unpack, and variables not unpacked are copied straight to output. HINT: If the name(s) of the input sparse-1D dimensions (e.g., \"column\", \"landunit\", and \"pft\") do not match NCO's preset defaults (case-insensitive unambiguous forms and abbreviations of \"column\", \"landunit\", and/or \"pft\", respectively) then change the dimension names that NCO looks for. Instructions are at http://nco.sf.net/nco.html#sparse. For CTSM/ELM sparse-1D coordinate grids, the \"column\", \"landunit\", and \"pft\" variable names can be set with, e.g., \"ncks --rgr column_nm=clm#landunit_nm=lnd#pft_nm=pft\" or \"ncremap -R '--rgr clm=clm#lnd=lnd#pft=pft'\".\n",nco_prg_nm_get(),fnc_nm); if(nco_dbg_lvl_get() >= nco_dbg_fl){ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr) (void)fprintf(stderr,"Unpack %s? %s\n",trv.nm,trv.flg_rgr ? "Yes" : "No"); } /* end idx_tbl */ } /* end dbg */ long clm_nbr_in=NC_MIN_INT; /* [nbr] Number of columns in input data */ long grd_nbr_in=NC_MIN_INT; /* [nbr] Number of gridcells in input data */ long lnd_nbr_in=NC_MIN_INT; /* [nbr] Number of landunits in input data */ long pft_nbr_in=NC_MIN_INT; /* [nbr] Number of PFTs in input data */ long clm_nbr_out=NC_MIN_INT; /* [nbr] Number of columns in output data */ long grd_nbr_out=NC_MIN_INT; /* [nbr] Number of gridcells in output data */ long lnd_nbr_out=NC_MIN_INT; /* [nbr] Number of landunits in output data */ long mec_nbr_out=NC_MIN_INT; /* [nbr] Number of MECs in output data */ long pft_nbr_out=NC_MIN_INT; /* [nbr] Number of PFTs in output data */ if(need_clm) rcd=nco_inq_dimlen(in_id,dmn_id_clm_in,&clm_nbr_in); if(need_grd) rcd=nco_inq_dimlen(in_id,dmn_id_grd_in,&grd_nbr_in); if(need_lnd) rcd=nco_inq_dimlen(in_id,dmn_id_lnd_in,&lnd_nbr_in); if(need_pft) rcd=nco_inq_dimlen(in_id,dmn_id_pft_in,&pft_nbr_in); int hrz_id; /* [id] Horizontal grid netCDF file ID */ long bnd_nbr=int_CEWI; /* [nbr] Number of boundaries for output time and rectangular grid coordinates, and number of vertices for output non-rectangular grid coordinates */ long col_nbr; /* [nbr] Number of columns */ long lon_nbr; /* [nbr] Number of longitudes */ long lat_nbr; /* [nbr] Number of latitudes */ size_t grd_sz_in; /* [nbr] Number of elements in single layer of input grid */ size_t grd_sz_out; /* [nbr] Number of elements in single layer of output grid */ if(flg_grd_dat) hrz_id=in_id; else hrz_id=tpl_id; /* Locate bounds dimension, if any, in file containing horizontal grid */ if(bnd_nm_in && (rcd=nco_inq_dimid_flg(hrz_id,bnd_nm_in,&dmn_id_bnd_in)) == NC_NOERR) /* do nothing */; else if((rcd=nco_inq_dimid_flg(hrz_id,"nv",&dmn_id_bnd_in)) == NC_NOERR) bnd_nm_in=strdup("nv"); /* fxm */ else if((rcd=nco_inq_dimid_flg(hrz_id,"nvertices",&dmn_id_bnd_in)) == NC_NOERR) bnd_nm_in=strdup("nvertices"); /* CICE */ else if((rcd=nco_inq_dimid_flg(hrz_id,"maxEdges",&dmn_id_bnd_in)) == NC_NOERR) bnd_nm_in=strdup("maxEdges"); /* MPAS */ if(flg_grd_1D) rcd=nco_inq_dimlen(hrz_id,dmn_id_col_in,&col_nbr); if(flg_grd_2D){ rcd=nco_inq_dimlen(hrz_id,dmn_id_lat_in,&lat_nbr); rcd=nco_inq_dimlen(hrz_id,dmn_id_lon_in,&lon_nbr); } /* !flg_grd_2D */ if(dmn_id_bnd_in != NC_MIN_INT) rcd=nco_inq_dimlen(hrz_id,dmn_id_bnd_in,&bnd_nbr); if(grd_nbr_in != NC_MIN_INT){ grd_sz_in=grd_nbr_in; }else{ grd_sz_in= flg_grd_1D ? col_nbr : lat_nbr*lon_nbr; } /* !grd_nbr_in */ grd_sz_out= flg_grd_1D ? col_nbr : lat_nbr*lon_nbr; /* Lay-out unpacked file */ char *bnd_nm_out=NULL; char *col_nm_out=NULL; char *lat_nm_out=NULL; char *lon_nm_out=NULL; char *lat_dmn_nm_out; char *lon_dmn_nm_out; int dmn_id_bnd_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_col_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lat_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lon_out=NC_MIN_INT; /* [id] Dimension ID */ if(rgr->bnd_nm) bnd_nm_out=rgr->bnd_nm; else bnd_nm_out=bnd_nm_in; if(rgr->col_nm_out) col_nm_out=rgr->col_nm_out; else col_nm_out=col_nm_in; if(rgr->lat_dmn_nm) lat_dmn_nm_out=rgr->lat_dmn_nm; else lat_dmn_nm_out=lat_nm_in; if(rgr->lon_dmn_nm) lon_dmn_nm_out=rgr->lon_dmn_nm; else lon_dmn_nm_out=lon_nm_in; if(rgr->lat_nm_out) lat_nm_out=rgr->lat_nm_out; else lat_nm_out=lat_nm_in; if(rgr->lon_nm_out) lon_nm_out=rgr->lon_nm_out; else lon_nm_out=lon_nm_in; /* Define horizontal dimensions before all else */ if(flg_grd_1D){ rcd=nco_def_dim(out_id,col_nm_out,col_nbr,&dmn_id_col_out); } /* !flg_grd_1D */ if(flg_grd_2D){ rcd=nco_def_dim(out_id,lat_nm_out,lat_nbr,&dmn_id_lat_out); rcd=nco_def_dim(out_id,lon_nm_out,lon_nbr,&dmn_id_lon_out); } /* !flg_grd_2D */ if(dmn_id_bnd_in != NC_MIN_INT) rcd=nco_def_dim(out_id,bnd_nm_out,bnd_nbr,&dmn_id_bnd_out); char *clm_nm_out=NULL; char *grd_nm_out=NULL; char *lnd_nm_out=NULL; char *pft_nm_out=NULL; if(need_clm) clm_nm_out=(char *)strdup(clm_nm_in); if(need_grd) grd_nm_out=(char *)strdup(grd_nm_in); if(need_lnd) lnd_nm_out=(char *)strdup(lnd_nm_in); if(need_pft) pft_nm_out=(char *)strdup(pft_nm_in); int dmn_id_clm_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_lnd_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_mec_out=NC_MIN_INT; /* [id] Dimension ID */ int dmn_id_pft_out=NC_MIN_INT; /* [id] Dimension ID */ /* fxm: make an ilun enumerated type? */ int ilun_vegetated_or_bare_soil; /* 1 [enm] */ int ilun_crop; /* 2 [enm] */ int ilun_landice; /* 3 [enm] */ int ilun_landice_multiple_elevation_classes; /* 4 [enm] */ int ilun_deep_lake; /* 5 [enm] */ int ilun_wetland; /* 6 [enm] */ int ilun_urban_tbd; /* 7 [enm] */ int ilun_urban_hd; /* 8 [enm] */ int ilun_urban_md; /* 9 [enm] */ if(flg_nm_hst){ rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_vegetated_or_bare_soil",&ilun_vegetated_or_bare_soil,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_crop",&ilun_crop,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_landice",&ilun_landice,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_landice_multiple_elevation_classes",&ilun_landice_multiple_elevation_classes,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_deep_lake",&ilun_deep_lake,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_wetland",&ilun_wetland,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_urban_tbd",&ilun_urban_tbd,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_urban_hd",&ilun_urban_hd,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ltype_urban_md",&ilun_urban_md,NC_INT); }else{ /* !flg_nm_hst */ rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_vegetated_or_bare_soil",&ilun_vegetated_or_bare_soil,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_crop",&ilun_crop,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_landice",&ilun_landice,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_landice_multiple_elevation_classes",&ilun_landice_multiple_elevation_classes,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_deep_lake",&ilun_deep_lake,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_wetland",&ilun_wetland,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_urban_tbd",&ilun_urban_tbd,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_urban_hd",&ilun_urban_hd,NC_INT); rcd=nco_get_att(in_id,NC_GLOBAL,"ilun_urban_md",&ilun_urban_md,NC_INT); } /* !flg_nm_hst */ /* Determine output Column dimension if needed */ int *cols1d_ityp=NULL; /* [id] Column type */ int *cols1d_ityplun=NULL; /* [id] Column landunit type */ if(need_clm){ if(cols1d_ityp_id != NC_MIN_INT) cols1d_ityp=(int *)nco_malloc(clm_nbr_in*sizeof(int)); cols1d_ityplun=(int *)nco_malloc(clm_nbr_in*sizeof(int)); if(cols1d_ityp_id != NC_MIN_INT) rcd=nco_get_var(in_id,cols1d_ityp_id,cols1d_ityp,NC_INT); rcd=nco_get_var(in_id,cols1d_ityplun_id,cols1d_ityplun,NC_INT); mec_nbr_out=0; for(clm_idx=0;clm_idx<clm_nbr_in;clm_idx++){ if(cols1d_ityplun[clm_idx] != ilun_landice_multiple_elevation_classes) continue; while(cols1d_ityplun[clm_idx++] == ilun_landice_multiple_elevation_classes) mec_nbr_out++; break; } /* !clm_idx */ /* NB: landice_MEC (ilun=4, usually) landunits have 10 (always, AFAICT) glacier elevation classes */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO mec_nbr_out = %ld\n",nco_prg_nm_get(),mec_nbr_out); } /* !need_clm */ /* Determine output Grid dimension if needed: CLM/ELM 'gridcell' dimension counts each gridcell that contains land Replace this dimension by horizontal dimension(s) in input data file */ if(need_clm){ if(flg_grd_1D) grd_nbr_out=col_nbr; if(flg_grd_2D) grd_nbr_out=lat_nbr*lon_nbr; if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO grd_nbr_out = %ld\n",nco_prg_nm_get(),grd_nbr_out); } /* !need_grd */ /* Determine output Landunit dimension if needed */ if(need_lnd){ lnd_nbr_out=3; /* fxm: Based on TBUILD variable for 3 urban landunit types */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO lnd_nbr_out = %ld\n",nco_prg_nm_get(),lnd_nbr_out); } /* !need_lnd */ /* Determine output PFT dimension if needed */ //double *pfts1d_wtgcell=NULL; /* [id] PFT weight relative to corresponding gridcell */ int *pfts1d_ityp_veg=NULL; /* [id] PFT vegetation type */ int *pfts1d_ityplun=NULL; /* [id] PFT landunit type */ int *pfts1d_ixy=NULL; /* [id] PFT 2D longitude index */ int *pfts1d_jxy=NULL; /* [id] PFT 2D latitude index */ int pft_typ; /* [enm] PFT type */ if(need_pft){ //pfts1d_wtgcell=(double *)nco_malloc(pft_nbr_in*sizeof(double)); pfts1d_ityp_veg=(int *)nco_malloc(pft_nbr_in*sizeof(int)); pfts1d_ityplun=(int *)nco_malloc(pft_nbr_in*sizeof(int)); //rcd=nco_get_var(in_id,pfts1d_wtgcell_id,pfts1d_wtgcell,NC_DOUBLE); rcd=nco_get_var(in_id,pfts1d_ityp_veg_id,pfts1d_ityp_veg,NC_INT); rcd=nco_get_var(in_id,pfts1d_ityplun_id,pfts1d_ityplun,NC_INT); pft_nbr_out=0; for(pft_idx=0;pft_idx<pft_nbr_in;pft_idx++){ if((pfts1d_ityplun[pft_idx] != ilun_vegetated_or_bare_soil) && (pfts1d_ityplun[pft_idx] != ilun_crop)) continue; /* Skip bare ground */ while(pfts1d_ityp_veg[++pft_idx] != 0) pft_nbr_out++; break; } /* !pft_idx */ if(nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: INFO pft_nbr_out = %ld\n",nco_prg_nm_get(),pft_nbr_out); pfts1d_ixy=(int *)nco_malloc(pft_nbr_in*sizeof(int)); rcd=nco_get_var(in_id,pfts1d_ixy_id,pfts1d_ixy,NC_INT); if(flg_grd_2D){ pfts1d_jxy=(int *)nco_malloc(pft_nbr_in*sizeof(int)); rcd=nco_get_var(in_id,pfts1d_jxy_id,pfts1d_jxy,NC_INT); } /* !flg_grd_2D */ } /* !need_pft */ /* Define unpacked versions of needed dimensions before all else */ (void)fprintf(stdout,"%s: DEBUG quark1\n",nco_prg_nm_get()); if(need_clm && clm_nbr_out > 0L) rcd=nco_def_dim(out_id,clm_nm_out,clm_nbr_out,&dmn_id_clm_out); if(need_lnd && lnd_nbr_out > 0L) rcd=nco_def_dim(out_id,lnd_nm_out,lnd_nbr_out,&dmn_id_lnd_out); if(need_pft && pft_nbr_out > 0L) rcd=nco_def_dim(out_id,pft_nm_out,pft_nbr_out,&dmn_id_pft_out); /* Assume MECs are new output dimension if they are enumerated in input */ if(mec_nbr_out > 0L) rcd=nco_def_dim(out_id,mec_nm_out,mec_nbr_out,&dmn_id_mec_out); /* Pre-allocate dimension ID and cnt/srt space */ char *var_nm; /* [sng] Variable name */ int *dmn_ids_in=NULL; /* [id] Dimension IDs */ int *dmn_ids_out=NULL; /* [id] Dimension IDs */ int dmn_nbr_max; /* [nbr] Maximum number of dimensions variable can have in input or output */ int var_id_in; /* [id] Variable ID */ int var_id_out; /* [id] Variable ID */ long *dmn_cnt_in=NULL; long *dmn_cnt_out=NULL; long *dmn_srt=NULL; nc_type var_typ; /* [enm] Variable type (same for input and output variable) */ nco_bool PCK_ATT_CPY=True; /* [flg] Copy attributes "scale_factor", "add_offset" */ int dmn_in_fst; /* [idx] Offset of input- relative to output-dimension due to non-MRV dimension insertion */ int dmn_nbr_rec; /* [nbr] Number of unlimited dimensions */ int *dmn_ids_rec=NULL; /* [id] Unlimited dimension IDs */ rcd+=nco_inq_ndims(in_id,&dmn_nbr_max); dmn_ids_in=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); dmn_ids_out=(int *)nco_malloc(dmn_nbr_max*sizeof(int)); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* Obtain record dimension information from data file (restart files have no time dimension) */ rcd+=nco_inq_unlimdims(in_id,&dmn_nbr_rec,(int *)NULL); if(dmn_nbr_rec > 0){ dmn_ids_rec=(int *)nco_malloc(dmn_nbr_rec*sizeof(int)); rcd=nco_inq_unlimdims(in_id,&dmn_nbr_rec,dmn_ids_rec); } /* !dmn_nbr_rec */ int shuffle; /* [flg] Turn-on shuffle filter */ int deflate; /* [flg] Turn-on deflate filter */ deflate=(int)True; shuffle=NC_SHUFFLE; dfl_lvl=rgr->dfl_lvl; fl_out_fmt=rgr->fl_out_fmt; //const int dmn_nbr_0D=0; /* [nbr] Rank of 0-D grid variables (scalars) */ const int dmn_nbr_1D=1; /* [nbr] Rank of 1-D grid variables */ const int dmn_nbr_2D=2; /* [nbr] Rank of 2-D grid variables */ nc_type crd_typ_in; nc_type crd_typ_out; /* Required grid variables */ int lat_in_id; /* [id] Variable ID for latitude */ int lat_out_id; /* [id] Variable ID for latitude */ int lon_in_id; /* [id] Variable ID for longitude */ int lon_out_id; /* [id] Variable ID for longitude */ rcd=nco_inq_varid(hrz_id,lat_nm_in,&lat_in_id); rcd=nco_inq_varid(hrz_id,lon_nm_in,&lon_in_id); rcd=nco_inq_vartype(hrz_id,lat_in_id,&crd_typ_in); /* NB: ELM/CLM history files default to NC_FLOAT for most grid variables To convert to NC_DOUBLE on output, also convert _FillValue attribute type consistently */ crd_typ_out=crd_typ_in; /* Optional grid variables */ char *area_nm; char *sgs_frc_nm; char *lat_bnd_nm; char *lon_bnd_nm; char *sgs_msk_nm; int area_in_id=NC_MIN_INT; /* [id] Variable ID for area */ int area_out_id=NC_MIN_INT; /* [id] Variable ID for area */ int sgs_frc_in_id=NC_MIN_INT; /* [id] Variable ID for fraction */ int sgs_frc_out_id=NC_MIN_INT; /* [id] Variable ID for fraction */ int lat_bnd_in_id=NC_MIN_INT; /* [id] Variable ID for latitude bounds */ int lat_bnd_out_id=NC_MIN_INT; /* [id] Variable ID for latitude bounds */ int lon_bnd_in_id=NC_MIN_INT; /* [id] Variable ID for longitude bounds */ int lon_bnd_out_id=NC_MIN_INT; /* [id] Variable ID for longitude bounds */ int sgs_msk_in_id=NC_MIN_INT; /* [id] Variable ID for mask */ int sgs_msk_out_id=NC_MIN_INT; /* [id] Variable ID for mask */ nco_bool flg_area_out=False; /* [flg] Add area to output */ nco_bool flg_lat_bnd_out=False; /* [flg] Add latitude bounds to output */ nco_bool flg_lon_bnd_out=False; /* [flg] Add longitude bounds to output */ nco_bool flg_sgs_frc_out=False; /* [flg] Add fraction to output */ nco_bool flg_sgs_msk_out=False; /* [flg] Add mask to output */ area_nm=rgr->area_nm ? rgr->area_nm : strdup("area"); lat_bnd_nm=rgr->lat_bnd_nm ? rgr->lat_bnd_nm : strdup("lat_bnd"); lon_bnd_nm=rgr->lon_bnd_nm ? rgr->lon_bnd_nm : strdup("lon_bnd"); sgs_frc_nm=rgr->sgs_frc_nm ? rgr->sgs_frc_nm : strdup("landfrac"); sgs_msk_nm=rgr->sgs_msk_nm ? rgr->sgs_msk_nm : strdup("landmask"); if((rcd=nco_inq_varid_flg(hrz_id,area_nm,&area_in_id)) == NC_NOERR) flg_area_out=True; if((rcd=nco_inq_varid_flg(hrz_id,lat_bnd_nm,&lat_bnd_in_id)) == NC_NOERR) flg_lat_bnd_out=True; if((rcd=nco_inq_varid_flg(hrz_id,lon_bnd_nm,&lon_bnd_in_id)) == NC_NOERR) flg_lon_bnd_out=True; if((rcd=nco_inq_varid_flg(hrz_id,sgs_frc_nm,&sgs_frc_in_id)) == NC_NOERR) flg_sgs_frc_out=True; if((rcd=nco_inq_varid_flg(hrz_id,sgs_msk_nm,&sgs_msk_in_id)) == NC_NOERR) flg_sgs_msk_out=True; (void)fprintf(stdout,"%s: DEBUG quark2\n",nco_prg_nm_get()); if(flg_grd_1D){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col_out,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lat_in_id,lat_out_id,PCK_ATT_CPY); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_col_out,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lon_in_id,lon_out_id,PCK_ATT_CPY); var_crt_nbr++; if(flg_lat_bnd_out){ dmn_ids_out[0]=dmn_id_col_out; dmn_ids_out[1]=dmn_id_bnd_out; rcd+=nco_def_var(out_id,lat_bnd_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lat_bnd_in_id,lat_bnd_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_lat_bnd_out */ if(flg_lon_bnd_out){ dmn_ids_out[0]=dmn_id_col_out; dmn_ids_out[1]=dmn_id_bnd_out; rcd+=nco_def_var(out_id,lon_bnd_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lon_bnd_in_id,lon_bnd_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_lon_bnd_out */ if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm,crd_typ_out,dmn_nbr_1D,&dmn_id_col_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,area_in_id,area_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_area_out */ if(flg_sgs_frc_out){ rcd+=nco_def_var(out_id,sgs_frc_nm,crd_typ_out,dmn_nbr_1D,&dmn_id_col_out,&sgs_frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,sgs_frc_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,sgs_frc_in_id,sgs_frc_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_sgs_frc_out */ if(flg_sgs_msk_out){ rcd+=nco_def_var(out_id,sgs_msk_nm,(nc_type)NC_INT,dmn_nbr_1D,&dmn_id_col_out,&sgs_msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,sgs_msk_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,sgs_msk_in_id,sgs_msk_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_sgs_msk_out */ } /* !flg_grd_1D */ if(flg_grd_2D){ rcd+=nco_def_var(out_id,lat_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lat_out,&lat_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lat_in_id,lat_out_id,PCK_ATT_CPY); var_crt_nbr++; rcd+=nco_def_var(out_id,lon_nm_out,crd_typ_out,dmn_nbr_1D,&dmn_id_lon_out,&lon_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lon_in_id,lon_out_id,PCK_ATT_CPY); var_crt_nbr++; if(flg_lat_bnd_out){ dmn_ids_out[0]=dmn_id_lat_out; dmn_ids_out[1]=dmn_id_bnd_out; rcd+=nco_def_var(out_id,lat_bnd_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lat_bnd_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lat_bnd_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lat_bnd_in_id,lat_bnd_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_lat_bnd_out */ if(flg_lon_bnd_out){ dmn_ids_out[0]=dmn_id_lon_out; dmn_ids_out[1]=dmn_id_bnd_out; rcd+=nco_def_var(out_id,lon_bnd_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&lon_bnd_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,lon_bnd_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,lon_bnd_in_id,lon_bnd_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_lon_bnd_out */ dmn_ids_out[0]=dmn_id_lat_out; dmn_ids_out[1]=dmn_id_lon_out; if(flg_area_out){ rcd+=nco_def_var(out_id,area_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&area_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,area_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,area_in_id,area_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_area_out */ if(flg_sgs_frc_out){ rcd+=nco_def_var(out_id,sgs_frc_nm,crd_typ_out,dmn_nbr_2D,dmn_ids_out,&sgs_frc_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,sgs_frc_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,sgs_frc_in_id,sgs_frc_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_sgs_frc_out */ if(flg_sgs_msk_out){ rcd+=nco_def_var(out_id,sgs_msk_nm,(nc_type)NC_INT,dmn_nbr_2D,dmn_ids_out,&sgs_msk_out_id); if(dfl_lvl > 0) (void)nco_def_var_deflate(out_id,sgs_msk_out_id,shuffle,deflate,dfl_lvl); (void)nco_att_cpy(hrz_id,out_id,sgs_msk_in_id,sgs_msk_out_id,PCK_ATT_CPY); var_crt_nbr++; } /* !flg_sgs_msk_out */ } /* !flg_grd_2D */ int flg_pck; /* [flg] Variable is packed on disk */ nco_bool has_mss_val; /* [flg] Has numeric missing value attribute */ nco_bool flg_add_spc_crd; /* [flg] Add spatial coordinates to S1D variable */ float mss_val_flt; double mss_val_dbl; nco_s1d_typ_enm nco_s1d_typ; /* [enm] Sparse-1D type of input variable */ aed_sct aed_mtd_fll_val; (void)fprintf(stdout,"%s: DEBUG quark3\n",nco_prg_nm_get()); /* Define unpacked S1D and copied variables in output file */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ var_nm=trv.nm; /* Preserve input type in output type */ var_typ=trv.var_typ; dmn_nbr_in=trv.nbr_dmn; dmn_nbr_out=trv.nbr_dmn; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid_flg(out_id,var_nm,&var_id_out); /* If variable has not been defined, define it */ if(rcd != NC_NOERR){ if(trv.flg_rgr){ /* Unpack */ (void)fprintf(stdout,"%s: DEBUG quark4\n",nco_prg_nm_get()); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_ids_in); dmn_in_fst=0; flg_add_spc_crd=False; rcd=nco_inq_var_packing(in_id,var_id_in,&flg_pck); if(flg_pck) (void)fprintf(stdout,"%s: WARNING %s reports S1D variable \"%s\" is packed so results unpredictable. HINT: If regridded values seems weird, retry after unpacking input file with, e.g., \"ncpdq -U in.nc out.nc\"\n",nco_prg_nm_get(),fnc_nm,var_nm); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); if(clm_nm_in && !strcmp(dmn_nm,clm_nm_in)){ if(mec_nbr_out > 0L){ /* Change input column dimension to MEC if present */ dmn_ids_out[dmn_idx]=dmn_id_mec_out; dmn_cnt_out[dmn_idx]=mec_nbr_out; dmn_in_fst++; dmn_nbr_out++; } /* !mec_nbr_out */ flg_add_spc_crd=True; }else if(!strcmp(dmn_nm,grd_nm_in)){ /* Gridcell dimension disappears to become spatial dimension in output */ flg_add_spc_crd=True; }else if(!strcmp(dmn_nm,lnd_nm_in)){ /* Change landunit dimension */ dmn_ids_out[dmn_idx]=dmn_id_lnd_out; dmn_cnt_out[dmn_idx]=lnd_nbr_out; flg_add_spc_crd=True; }else if(!strcmp(dmn_nm,pft_nm_in)){ if(pft_nbr_out > 0L){ /* Change input PFT dimension to PFT if present */ dmn_ids_out[dmn_idx]=dmn_id_pft_out; dmn_cnt_out[dmn_idx]=pft_nbr_out; dmn_in_fst++; dmn_nbr_out++; } /* !pft_nbr_out */ flg_add_spc_crd=True; }else{ /* Dimensions [clm/lnd/pft]_nm_in were pre-defined above as [clm/lnd/pft]_nm_out, replicate all other dimensions */ rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_ids_out+dmn_idx); } /* !clm */ if(rcd != NC_NOERR){ /* Current input dimension is not yet in output file */ (void)fprintf(stdout,"%s: DEBUG var_nm = %s, dmn_nm = %s\n",nco_prg_nm_get(),var_nm,dmn_nm); rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_ids_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); } /* !rcd */ if(flg_add_spc_crd){ /* Follow by spatial dimension(s) */ if(flg_grd_1D){ dmn_ids_out[dmn_idx+dmn_in_fst]=dmn_id_col_out; dmn_cnt_out[dmn_idx+dmn_in_fst]=col_nbr; } /* !flg_grd_1D */ if(flg_grd_2D){ dmn_ids_out[dmn_idx+dmn_in_fst]=dmn_id_lat_out; dmn_cnt_out[dmn_idx+dmn_in_fst]=lat_nbr; dmn_in_fst++; dmn_nbr_out++; dmn_ids_out[dmn_idx+dmn_in_fst]=dmn_id_lon_out; dmn_cnt_out[dmn_idx+dmn_in_fst]=lon_nbr; } /* !flg_grd_2D */ } /* !flg_add_spc_crd */ } /* !dmn_idx */ }else{ /* !flg_rgr */ /* Replicate non-S1D variables */ (void)fprintf(stdout,"%s: DEBUG quark5\n",nco_prg_nm_get()); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_ids_in); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimname(in_id,dmn_ids_in[dmn_idx],dmn_nm); rcd=nco_inq_dimid_flg(out_id,dmn_nm,dmn_ids_out+dmn_idx); if(rcd != NC_NOERR){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_out+dmn_idx); /* Check-for and, if found, retain record dimension property */ for(int dmn_rec_idx=0;dmn_rec_idx < dmn_nbr_rec;dmn_rec_idx++) if(dmn_ids_in[dmn_idx] == dmn_ids_rec[dmn_rec_idx]) dmn_cnt_out[dmn_idx]=NC_UNLIMITED; rcd=nco_def_dim(out_id,dmn_nm,dmn_cnt_out[dmn_idx],dmn_ids_out+dmn_idx); } /* !rcd */ } /* !dmn_idx */ } /* !flg_rgr */ (void)fprintf(stdout,"%s: DEBUG quark6 defining %s...\n",nco_prg_nm_get(),var_nm); rcd=nco_def_var(out_id,var_nm,var_typ,dmn_nbr_out,dmn_ids_out,&var_id_out); (void)fprintf(stdout,"%s: DEBUG quark7 defined %s\n",nco_prg_nm_get(),var_nm); /* Duplicate netCDF4 settings when possible */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC){ /* Deflation */ if(dmn_nbr_out > 0){ int dfl_lvl_in; /* [enm] Deflate level [0..9] */ rcd=nco_inq_var_deflate(in_id,var_id_in,&shuffle,&deflate,&dfl_lvl_in); /* Before netCDF 4.8.0, nco_def_var_deflate() could be called multiple times Properties of final invocation before nc_enddef() would take effect After netCDF 4.8.0 first instance of nco_def_var_deflate() takes effect */ if((deflate || shuffle) && dfl_lvl < 0){ /* Copy original filters if user did not explicity set dfl_lvl for output */ (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl_in); }else if(dfl_lvl >= 0){ /* Overwrite HDF Lempel-Ziv compression level, if requested */ deflate=(int)True; /* Turn-off shuffle when uncompressing otherwise chunking requests may fail */ if(dfl_lvl <= 0) shuffle=NC_NOSHUFFLE; /* Shuffle never, to my knowledge, increases filesize, so shuffle by default when manually deflating (and do not shuffle when uncompressing) */ if(dfl_lvl > 0) shuffle=NC_SHUFFLE; (void)nco_def_var_deflate(out_id,var_id_out,shuffle,deflate,dfl_lvl); } /* !dfl_lvl */ } /* !dmn_nbr_out */ } /* !NC_FORMAT_NETCDF4 */ (void)nco_att_cpy(in_id,out_id,var_id_in,var_id_out,PCK_ATT_CPY); /* Variables with subterranean levels and missing-value extrapolation must have _FillValue attribute */ (void)fprintf(stdout,"%s: DEBUG quark8\n",nco_prg_nm_get()); nco_bool flg_add_msv_att; /* [flg] Extrapolation requires _FillValue */ flg_add_msv_att=False; if(flg_add_msv_att && trv.flg_rgr){ has_mss_val=nco_mss_val_get_dbl(in_id,var_id_in,&mss_val_dbl); if(!has_mss_val){ nco_bool flg_att_chg; /* [flg] _FillValue attribute was written */ aed_mtd_fll_val.var_nm=var_nm; aed_mtd_fll_val.id=var_id_out; aed_mtd_fll_val.type=var_typ; if(var_typ == NC_FLOAT) aed_mtd_fll_val.val.fp=&mss_val_flt; else if(var_typ == NC_DOUBLE) aed_mtd_fll_val.val.dp=&mss_val_dbl; flg_att_chg=nco_aed_prc(out_id,var_id_out,aed_mtd_fll_val); if(!flg_att_chg && nco_dbg_lvl_get() >= nco_dbg_std) (void)fprintf(stdout,"%s: WARNING %s reports unsuccessful attempt to create _FillValue attribute for variable %s\n",nco_prg_nm_get(),fnc_nm,var_nm); } /* !has_mss_val */ } /* !flg_add_msv_att */ } /* !rcd */ } /* !var */ } /* end idx_tbl */ (void)fprintf(stdout,"%s: DEBUG quark9\n",nco_prg_nm_get()); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Begin data mode */ (void)nco_enddef(out_id); /* Copy coordinate system before closing template file NB: nco_cpy_var_val() cannot be used here when coordinates are in fl_tpl not fl_in */ (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,lat_nm_in,(lmt_sct *)NULL,(int)0); (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,lon_nm_in,(lmt_sct *)NULL,(int)0); if(flg_lat_bnd_out) (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,lat_bnd_nm,(lmt_sct *)NULL,(int)0); if(flg_lon_bnd_out) (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,lon_bnd_nm,(lmt_sct *)NULL,(int)0); if(flg_sgs_frc_out) (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,sgs_frc_nm,(lmt_sct *)NULL,(int)0); if(flg_sgs_msk_out) (void)nco_cpy_var_val_lmt(hrz_id,out_id,(FILE *)NULL,sgs_msk_nm,(lmt_sct *)NULL,(int)0); if(flg_grd_tpl){ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ /* No further access to template file, close it */ nco_close(tpl_id); /* Remove local copy of file */ if(FL_RTR_RMT_LCN && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_tpl); } /* !flg_grd_tpl */ /* Free pre-allocated array space */ if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_ids_out) dmn_ids_out=(int *)nco_free(dmn_ids_out); if(dmn_ids_rec) dmn_ids_rec=(int *)nco_free(dmn_ids_rec); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); /* Unpack and copy data from input file */ //int dmn_idx_col=int_CEWI; /* [idx] Index of column dimension */ //int dmn_idx_lat=int_CEWI; /* [idx] Index of latitude dimension */ //int dmn_idx_lon=int_CEWI; /* [idx] Index of longitude dimension */ int thr_idx; /* [idx] Thread index */ //int var_id; /* [id] Current variable ID */ size_t var_sz_in; /* [nbr] Number of elements in variable (will be self-multiplied) */ size_t var_sz_out; /* [nbr] Number of elements in variable (will be self-multiplied) */ ptr_unn var_val_in; ptr_unn var_val_out; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped as shared in parallel clause */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ #ifdef __GNUG__ # pragma omp parallel for firstprivate(var_val_in,var_val_out) private(dmn_cnt_in,dmn_cnt_out,dmn_ids_in,dmn_ids_out,dmn_idx,dmn_nbr_in,dmn_nbr_out,dmn_nbr_max,dmn_nm,dmn_srt,has_clm,has_grd,has_lnd,has_pft,has_mss_val,idx_out,idx_tbl,in_id,mss_val_dbl,rcd,thr_idx,trv,var_id_in,var_id_out,var_nm,var_sz_in,var_sz_out,var_typ) shared(dmn_id_clm_in,dmn_id_clm_out,dmn_id_col_in,dmn_id_col_out,dmn_id_lat_in,dmn_id_lat_out,dmn_id_lnd_in,dmn_id_lnd_out,dmn_id_lon_in,dmn_id_lon_out,dmn_id_pft_in,dmn_id_pft_out,flg_s1d_clm,flg_s1d_pft,clm_nbr_in,clm_nbr_out,col_nbr,lat_nbr,lnd_nbr_in,lnd_nbr_out,lon_nbr,pft_nbr_in,pft_nbr_out,out_id,pfts1d_ixy,pfts1d_jxy) #endif /* !__GNUG__ */ for(idx_tbl=0;idx_tbl<trv_nbr;idx_tbl++){ trv=trv_tbl->lst[idx_tbl]; thr_idx=omp_get_thread_num(); in_id=trv_tbl->in_id_arr[thr_idx]; #ifdef _OPENMP if(nco_dbg_lvl_get() >= nco_dbg_grp && !thr_idx && !idx_tbl) (void)fprintf(fp_stdout,"%s: INFO %s reports regrid loop uses %d thread%s\n",nco_prg_nm_get(),fnc_nm,omp_get_num_threads(),(omp_get_num_threads() > 1) ? "s" : ""); if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s: INFO thread = %d, idx_tbl = %d, nm = %s\n",nco_prg_nm_get(),thr_idx,idx_tbl,trv.nm); #endif /* !_OPENMP */ if(trv.nco_typ == nco_obj_typ_var && trv.flg_xtr){ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(fp_stdout,"%s%s ",trv.flg_rgr ? "#" : "~",trv.nm); if(trv.flg_rgr){ /* Unpack variable */ var_nm=trv.nm; var_typ=trv.var_typ; /* NB: Output type in file is same as input type */ var_sz_in=1L; var_sz_out=1L; rcd=nco_inq_varid(in_id,var_nm,&var_id_in); rcd=nco_inq_varid(out_id,var_nm,&var_id_out); rcd=nco_inq_varndims(in_id,var_id_in,&dmn_nbr_in); rcd=nco_inq_varndims(out_id,var_id_out,&dmn_nbr_out); dmn_nbr_max= dmn_nbr_in > dmn_nbr_out ? dmn_nbr_in : dmn_nbr_out; dmn_ids_in=(int *)nco_malloc(dmn_nbr_in*sizeof(int)); dmn_ids_out=(int *)nco_malloc(dmn_nbr_out*sizeof(int)); dmn_srt=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); /* max() for both input and output grids */ dmn_cnt_in=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); dmn_cnt_out=(long *)nco_malloc(dmn_nbr_max*sizeof(long)); rcd=nco_inq_vardimid(in_id,var_id_in,dmn_ids_in); rcd=nco_inq_vardimid(out_id,var_id_out,dmn_ids_out); for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ rcd=nco_inq_dimlen(in_id,dmn_ids_in[dmn_idx],dmn_cnt_in+dmn_idx); var_sz_in*=dmn_cnt_in[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ for(dmn_idx=0;dmn_idx<dmn_nbr_out;dmn_idx++){ rcd=nco_inq_dimlen(out_id,dmn_ids_out[dmn_idx],dmn_cnt_out+dmn_idx); if(dmn_cnt_out[dmn_idx] == 0L){ /* No records have been written, so overwrite zero output record size with input record size */ char dmn_rec_nm[NC_MAX_NAME]; /* [sng] Record dimension name */ int dmn_rec_id_in; rcd=nco_inq_dimname(out_id,dmn_ids_out[dmn_idx],dmn_rec_nm); rcd=nco_inq_dimid(in_id,dmn_rec_nm,&dmn_rec_id_in); rcd=nco_inq_dimlen(in_id,dmn_rec_id_in,dmn_cnt_out+dmn_idx); } /* !dmn_cnt_out */ var_sz_out*=dmn_cnt_out[dmn_idx]; dmn_srt[dmn_idx]=0L; } /* !dmn_idx */ var_val_in.vp=(void *)nco_malloc_dbg(var_sz_in*nco_typ_lng(var_typ),fnc_nm,"Unable to malloc() input value buffer"); var_val_out.vp=(void *)nco_malloc_dbg(var_sz_out*nco_typ_lng(var_typ),fnc_nm,"Unable to malloc() output value buffer"); /* Initialize output */ (void)memset(var_val_out.vp,0,var_sz_out*nco_typ_lng(var_typ)); /* Obtain input variable */ rcd=nco_get_vara(in_id,var_id_in,dmn_srt,dmn_cnt_in,var_val_in.vp,var_typ); has_clm=has_grd=has_lnd=has_pft=False; nco_s1d_typ=nco_s1d_nil; for(dmn_idx=0;dmn_idx<dmn_nbr_in;dmn_idx++){ dmn_nm_cp=trv.var_dmn[dmn_idx].dmn_nm; if(!has_clm && clm_nm_in) has_clm=!strcmp(dmn_nm_cp,clm_nm_in); if(!has_grd && grd_nm_in) has_grd=!strcmp(dmn_nm_cp,grd_nm_in); if(!has_lnd && lnd_nm_in) has_lnd=!strcmp(dmn_nm_cp,lnd_nm_in); if(!has_pft && pft_nm_in) has_pft=!strcmp(dmn_nm_cp,pft_nm_in); } /* !dmn_idx */ if(has_clm) nco_s1d_typ=nco_s1d_clm; else if(has_grd) nco_s1d_typ=nco_s1d_grd; else if(has_lnd) nco_s1d_typ=nco_s1d_lnd; else if(has_pft) nco_s1d_typ=nco_s1d_pft; else{ (void)fprintf(stderr,"%s: ERROR %s reports variable %s does not appear to be sparse\n",nco_prg_nm_get(),fnc_nm,var_nm); nco_exit(EXIT_FAILURE); } /* !strstr() */ if(nco_dbg_lvl_get() >= nco_dbg_std){ (void)fprintf(stderr,"%s: INFO %s reports variable %s is sparse type %s\n",nco_prg_nm_get(),fnc_nm,var_nm,nco_s1d_sng(nco_s1d_typ)); } /* !dbg */ /* The Hard Work */ if(nco_s1d_typ == nco_s1d_pft){ /* Turn GPP(time,pft) into GPP(time,pft,lndgrid) */ for(pft_idx=0;pft_idx<pft_nbr_in;pft_idx++){ pft_typ=pfts1d_ityp_veg[pft_idx]; /* [1 <= pft_typ <= pft_nbr_out] */ /* Skip bare ground, output array contains only vegetated types */ if(!pft_typ) continue; /* grd_idx is the index relative to the origin of the horizontal grid for a given level [0 <= grd_idx_out <= col_nbr_out-1L], [1 <= pfts1d_ixy <= col_nbr_out] */ grd_idx_out= flg_grd_1D ? pfts1d_ixy[pft_idx]-1L : (pfts1d_ixy[pft_idx]-1L)*lat_nbr+(pfts1d_jxy[pft_idx]-1L); idx_out=(pft_typ-1)*grd_sz_out+grd_idx_out; /* memcpy() would allow next statement to work for generic types However, memcpy() is a system call and could be expensive in an innermost loop */ switch(var_typ){ case NC_FLOAT: var_val_out.fp[idx_out]=var_val_in.fp[pft_idx]; break; case NC_DOUBLE: var_val_out.dp[idx_out]=var_val_in.dp[pft_idx]; break; case NC_INT: var_val_out.ip[idx_out]=var_val_in.ip[pft_idx]; break; default: (void)fprintf(fp_stdout,"%s: ERROR %s reports unsupported type\n",nco_prg_nm_get(),fnc_nm); nco_dfl_case_nc_type_err(); break; } /* !var_typ */ } /* !idx */ } /* !nco_s1d_typ */ #pragma omp critical { /* begin OpenMP critical */ rcd=nco_put_vara(out_id,var_id_out,dmn_srt,dmn_cnt_out,var_val_out.vp,var_typ); } /* end OpenMP critical */ if(dmn_ids_in) dmn_ids_in=(int *)nco_free(dmn_ids_in); if(dmn_ids_out) dmn_ids_out=(int *)nco_free(dmn_ids_out); if(dmn_srt) dmn_srt=(long *)nco_free(dmn_srt); if(dmn_cnt_in) dmn_cnt_in=(long *)nco_free(dmn_cnt_in); if(dmn_cnt_out) dmn_cnt_out=(long *)nco_free(dmn_cnt_out); if(var_val_in.vp) var_val_in.vp=(void *)nco_free(var_val_in.vp); if(var_val_out.vp) var_val_out.vp=(void *)nco_free(var_val_out.vp); }else{ /* !trv.flg_rgr */ /* Use standard NCO copy routine for variables that are not regridded 20190511: Copy them only once */ #pragma omp critical { /* begin OpenMP critical */ (void)nco_cpy_var_val(in_id,out_id,(FILE *)NULL,(md5_sct *)NULL,trv.nm,trv_tbl); } /* end OpenMP critical */ } /* !flg_rgr */ } /* !xtr */ } /* end (OpenMP parallel for) loop over idx_tbl */ if(nco_dbg_lvl_get() >= nco_dbg_var) (void)fprintf(stdout,"\n"); if(nco_dbg_lvl_get() >= nco_dbg_fl) (void)fprintf(stdout,"%s: INFO %s completion report: Variables interpolated = %d, copied unmodified = %d, omitted = %d, created = %d\n",nco_prg_nm_get(),fnc_nm,var_rgr_nbr,var_cpy_nbr,var_xcl_nbr,var_crt_nbr); /* Free output data memory */ if(cols1d_ityp) cols1d_ityp=(int *)nco_free(cols1d_ityp); if(cols1d_ityplun) cols1d_ityplun=(int *)nco_free(cols1d_ityplun); if(pfts1d_ityp_veg) pfts1d_ityp_veg=(int *)nco_free(pfts1d_ityp_veg); if(pfts1d_ityplun) pfts1d_ityplun=(int *)nco_free(pfts1d_ityplun); if(pfts1d_ixy) pfts1d_ixy=(int *)nco_free(pfts1d_ixy); if(pfts1d_jxy) pfts1d_jxy=(int *)nco_free(pfts1d_jxy); //if(pfts1d_wtgcell) pfts1d_wtgcell=(double *)nco_free(pfts1d_wtgcell); if(clm_nm_in) clm_nm_in=(char *)nco_free(clm_nm_in); if(grd_nm_in) grd_nm_in=(char *)nco_free(grd_nm_in); if(lnd_nm_in) lnd_nm_in=(char *)nco_free(lnd_nm_in); if(pft_nm_in) pft_nm_in=(char *)nco_free(pft_nm_in); if(clm_nm_out) clm_nm_out=(char *)nco_free(clm_nm_out); if(grd_nm_out) grd_nm_out=(char *)nco_free(grd_nm_out); if(lnd_nm_out) lnd_nm_out=(char *)nco_free(lnd_nm_out); if(pft_nm_out) pft_nm_out=(char *)nco_free(pft_nm_out); return rcd; } /* !nco_s1d_unpack() */
core_zsyssq.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include <plasma_core_blas.h> #include "plasma_types.h" #include "core_lapack.h" #include <math.h> /******************************************************************************/ __attribute__((weak)) void plasma_core_zsyssq(plasma_enum_t uplo, int n, const plasma_complex64_t *A, int lda, double *scale, double *sumsq) { int ione = 1; if (uplo == PlasmaUpper) { for (int j = 1; j < n; j++) // TODO: Inline this operation. LAPACK_zlassq(&j, &A[lda*j], &ione, scale, sumsq); } else { // PlasmaLower for (int j = 0; j < n-1; j++) { int len = n-j-1; // TODO: Inline this operation. LAPACK_zlassq(&len, &A[lda*j+j+1], &ione, scale, sumsq); } } *sumsq *= 2.0; for (int i = 0; i < n; i++) { // diagonal is complex, don't ignore complex part double absa = cabs(A[lda*i+i]); if (absa != 0.0) { // != propagates nan if (*scale < absa) { *sumsq = 1.0 + *sumsq*((*scale/absa)*(*scale/absa)); *scale = absa; } else { *sumsq = *sumsq + ((absa/(*scale))*(absa/(*scale))); } } } } /******************************************************************************/ void plasma_core_omp_zsyssq(plasma_enum_t uplo, int n, const plasma_complex64_t *A, int lda, double *scale, double *sumsq, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:A[0:lda*n]) \ depend(out:scale[0:n]) \ depend(out:sumsq[0:n]) { if (sequence->status == PlasmaSuccess) { *scale = 0.0; *sumsq = 1.0; plasma_core_zsyssq(uplo, n, A, lda, scale, sumsq); } } } /******************************************************************************/ void plasma_core_omp_zsyssq_aux(int m, int n, const double *scale, const double *sumsq, double *value, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(in:scale[0:n]) \ depend(in:sumsq[0:n]) \ depend(out:value[0:1]) { if (sequence->status == PlasmaSuccess) { double scl = 0.0; double sum = 1.0; for (int j = 0; j < n; j++) { for (int i = j+1; i < n; i++) { int idx = m*j+i; if (scl < scale[idx]) { sum = sumsq[idx] + sum*((scl/scale[idx])*(scl/scale[idx])); scl = scale[idx]; } else { sum = sum + sumsq[idx]*((scale[idx]/scl)*(scale[idx]/scl)); } } } sum = 2.0*sum; for (int j = 0; j < n; j++) { int idx = m*j+j; if (scl < scale[idx]) { sum = sumsq[idx] + sum*((scl/scale[idx])*(scl/scale[idx])); scl = scale[idx]; } else { sum = sum + sumsq[idx]*((scale[idx]/scl)*(scale[idx]/scl)); } } *value = scl*sqrt(sum); } } }
scalespace_filter_impl.h
/* The MIT License (MIT) * * (c) Jürgen Simon 2014 (juergen.simon@uni-bonn.de) * * 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. */ #ifndef M3D_SCALESPACEFILTER_IMPL_H #define M3D_SCALESPACEFILTER_IMPL_H #include <meanie3D/defines.h> #include <meanie3D/namespaces.h> #include <meanie3D/parallel.h> #include <meanie3D/utils.h> #include <exception> #include <stdexcept> #include <cmath> #include <map> #include <string> #include <boost/progress.hpp> #include "scalespace_filter.h" namespace m3D { using namespace std; #pragma mark - #pragma mark Utility methods template<typename T> T ScaleSpaceFilter<T>::scale_to_filter_width(T t, T decay) { T filter_width = sqrt(ceil(-2.0 * t * log(decay))) / 2.0; return filter_width; } template<typename T> T ScaleSpaceFilter<T>::filter_width_to_scale(T width, T decay) { T scale = -2.0 * width * width / log(decay); return scale; } #pragma mark - #pragma mark Constructor/Destructor template<typename T> ScaleSpaceFilter<T>::ScaleSpaceFilter(T scale, const vector<T> &resolution, const vector<string> &excluded_vars, T decay, bool show_progress) : FeatureSpaceFilter<T>(show_progress), m_scale(scale), m_decay(decay), m_progress_bar(NULL), m_excluded_vars(excluded_vars) { if (scale < 0) { throw logic_error("scale can not be less than zero"); } if (decay < 0 || decay >= 1) { throw logic_error("decay must be > 0 and < 1"); } T filter_width = sqrt(ceil(-2.0 * scale * log(decay))) / 2; m_kernels.clear(); for (size_t i = 0; i < resolution.size(); i++) { // calculate the distances vector size_t mask_size = filter_width / resolution[i]; vector<T> distances(mask_size, 0.0); for (size_t j = 0; j < mask_size; j++) { distances[j] = ((T) j) * resolution[i]; } // create the kernel ScaleSpaceKernel<T> kernel(scale, distances); m_kernels.push_back(kernel); } } template<typename T> ScaleSpaceFilter<T>::~ScaleSpaceFilter() { } #pragma mark - #pragma mark Abstract filter method template<typename T> void ScaleSpaceFilter<T>::applyWithArrayIndexRecursive(FeatureSpace <T> *fs, ArrayIndex <T> *originalIndex, ArrayIndex <T> *filteredPoints, vector<size_t> &dimensionIndexes, size_t dimensionIndex, typename CoordinateSystem<T>::GridPoint &gridpoint) { // loop over the dimension with the given index. For each // coordinate, loop over the other two. At Each point, apply // the one-dimensional kernel using namespace std; const CoordinateSystem<T> *cs = fs->coordinate_system; size_t realDimIndex = dimensionIndexes[dimensionIndex]; NcDim dim = cs->dimensions()[realDimIndex]; // iterate over dimensions for (int index = 0; index < dim.getSize(); index++) { gridpoint[realDimIndex] = index; if (dimensionIndex < (gridpoint.size() - 1)) { applyWithArrayIndexRecursive(fs, originalIndex, filteredPoints, dimensionIndexes, dimensionIndex + 1, gridpoint); } else { // we reached the fixed dimension if (this->show_progress()) { m_progress_bar->operator++(); } // exclude points that were off limits // in any of the original data sets //if (fs->off_limits()->get(gridpoint)) // continue; ScaleSpaceKernel<T> g = this->m_kernels[realDimIndex]; // Find the boundaries. Take care not to step // outside the bounds of the array int width = g.values().size() - 1; int gpIndex = (int) gridpoint[realDimIndex]; int minIndex = (gpIndex - width >= 0) ? (gpIndex - width) : 0; int maxIndex = ((gpIndex + width) < (dim.getSize() - 1)) ? (gpIndex + width) : (dim.getSize() - 1); // Convolute in 1D around the given point with // the mask size determined by the kernel // Run the convolution for each feature variable typename CoordinateSystem<T>::GridPoint gridIter = gridpoint; vector<T> sum(fs->value_rank(), 0.0); size_t sumCount = 0; for (int i = minIndex; i < maxIndex; i++) { // set gridpoint to current position gridIter[realDimIndex] = i; // Again, make sure no points originally marked as // off limits are used // if (fs->off_limits()->get(gridIter)) // continue; // get the point at the iterated position Point<T> *pIter = originalIndex->get(gridIter); if (pIter == NULL) continue; // apply the pre-sampled gaussian and sum up size_t d = (i <= index) ? (index - i) : (i - index); for (int varIndex = 0; varIndex < fs->value_rank(); varIndex++) { T value = pIter->values[cs->rank() + varIndex]; sum[varIndex] += g.value(d) * value; } sumCount++; } // No muss, no fuss if (sumCount == 0) continue; // Fuss! Fetch the point from the array index Point<T> *p = filteredPoints->get(gridpoint); // If no point existed, decide if we need to create one if (p == NULL) { // Create a new point with default values // and insert into array index typename CoordinateSystem<T>::Coordinate coordinate = cs->newCoordinate(); cs->lookup(gridpoint, coordinate); vector<T> values = coordinate; values.resize(fs->rank(), 0.0); p = PointFactory<T>::get_instance()->create(gridpoint, coordinate, values); // Did this exist in the original index? Point<T> *op = originalIndex->get(gridpoint); p->isOriginalPoint = ((op == NULL) ? false : op->isOriginalPoint); // Since we just created this point, there // is no need to copy it again when adding // it to the array index filteredPoints->set(gridpoint, p, false); } // If we have a point after all that, update it with the // filtered value if (p != NULL) { // copy values and track limits for (int varIndex = 0; varIndex < fs->value_rank(); varIndex++) { p->values[fs->spatial_rank() + varIndex] = sum[varIndex]; if (sum[varIndex] < m_min[varIndex]) m_min[varIndex] = sum[varIndex]; if (sum[varIndex] > m_max[varIndex]) m_max[varIndex] = sum[varIndex]; } } } } } template<typename T> void ScaleSpaceFilter<T>::applyWithArrayIndexForDimension(FeatureSpace <T> *fs, ArrayIndex <T> *originalIndex, ArrayIndex <T> *filteredPoints, size_t fixedDimensionIndex) { // iterate over the other two // Create a vector, that enumerates the dimensions such, that the // fixed dimension comes last vector<size_t> dimensionIndexes; for (size_t j = 0; j < fs->coordinate_system->rank(); j++) { if (j == fixedDimensionIndex) continue; dimensionIndexes.push_back(j); } dimensionIndexes.push_back(fixedDimensionIndex); typename CoordinateSystem<T>::GridPoint gridpoint = fs->coordinate_system->newGridPoint(); // Now recurse into the structure, bearing in mind that // the dimensions have been re-ordered applyWithArrayIndexRecursive(fs, originalIndex, filteredPoints, dimensionIndexes, 0, gridpoint); } template<typename T> void ScaleSpaceFilter<T>::applyWithArrayIndex(FeatureSpace <T> *fs) { using namespace std; const CoordinateSystem<T> *cs = fs->coordinate_system; // index the original if (this->show_progress()) { cout << endl << "Constructing array indexes ..."; start_timer(); } ArrayIndex<T> *originalIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), fs->points, true); ArrayIndex<T> *filteredIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), false); if (this->show_progress()) { cout << "done. (" << stop_timer() << "s)" << endl; } if (this->show_progress()) { cout << endl << "Applying scale filter t=" << m_scale << " decay=" << m_decay << " ... " << endl; long numPoints = 1; for (size_t i = 0; i < fs->coordinate_system->rank(); i++) { numPoints *= fs->coordinate_system->dimensions()[i].getSize(); } m_progress_bar = new boost::progress_display(fs->spatial_rank() * numPoints); start_timer(); } // initialize min/max and re-set counts for (size_t varIndex = 0; varIndex < fs->value_rank(); varIndex++) { m_min[varIndex] = std::numeric_limits<T>::max(); m_max[varIndex] = std::numeric_limits<T>::min(); } // Apply dimension by dimension (exploiting separability) for (size_t dimIndex = 0; dimIndex < fs->spatial_rank(); dimIndex++) { applyWithArrayIndexForDimension(fs, originalIndex, filteredIndex, dimIndex); delete originalIndex; if (dimIndex < (fs->spatial_rank() - 1)) { originalIndex = filteredIndex; filteredIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), false); } } // replace the points in the original with the filtered // array index results filteredIndex->replace_points(fs->points); size_t originalPoints = 0; for (size_t i = 0; i < fs->points.size(); i++) { if (fs->points[i]->isOriginalPoint) originalPoints++; } if (this->show_progress()) { cout << "done. (" << stop_timer() << "s)" << endl; cout << "Filtered featurespace contains " << fs->size() << " points (" << originalPoints << " original points, " << "(" << (fs->size() - originalPoints) << " new points))" << endl; delete m_progress_bar; m_progress_bar = NULL; } // Clean up delete filteredIndex; } template<typename T> void ScaleSpaceFilter<T>::apply_parallellized_on_dimension(FeatureSpace <T> *fs, ArrayIndex <T> *originalIndex, ArrayIndex <T> *filteredPoints, size_t fixedDimension) { using namespace std; const CoordinateSystem<T> *cs = fs->coordinate_system; const vector<size_t> dim_sizes = cs->get_dimension_sizes(); const size_t numDims = cs->rank(); const size_t value_rank = fs->value_rank(); // Collate the dimension sizes for the linear mapping // and the dimension indexes std::vector<size_t> iter_dimensions; for (size_t i = 0; i < dim_sizes.size(); i++) if (i != fixedDimension) iter_dimensions.push_back(dim_sizes[i]); LinearIndexMapping mapping(iter_dimensions); size_t N = mapping.size(); #if WITH_OPENMP #pragma omp parallel for schedule(dynamic) #endif for (size_t n = 0; n < N; n++) { // re-assemble the starting point for the iteration from // the mapping's components vector<int> truncatedGridPoint = mapping.linear_to_grid(n); vector<int> startPoint(cs->rank()); size_t runningIndex = 0; for (size_t i = 0; i < cs->rank(); i++) if (i != fixedDimension) startPoint[i] = truncatedGridPoint[runningIndex++]; size_t fixedDimSize = dim_sizes[fixedDimension]; // Now iterate over the remaining dimension // TODO: consider to nest this depending on // problem size for (size_t k = 0; k < dim_sizes[fixedDimension]; k++) { if (this->show_progress()) { #if WITH_OPENMP #pragma omp critical #endif m_progress_bar->operator++(); } // construct position vector<int> gridpoint(startPoint); gridpoint[fixedDimension] = k; #if SCALE_SPACE_SKIPS_NON_ORIGINAL_POINTS if (fs->off_limits()->get(gridpoint)) continue; #endif ScaleSpaceKernel<T> g = this->m_kernels[fixedDimension]; // Find the boundaries. Take care not to step // outside the bounds of the array int width = g.values().size() - 1; int gpIndex = (int) gridpoint[fixedDimension]; int minIndex = (gpIndex - width >= 0) ? (gpIndex - width) : 0; int maxIndex = ((gpIndex + width) < (fixedDimSize - 1)) ? (gpIndex + width) : (fixedDimSize - 1); // Convolute in 1D around the given point with // the mask size determined by the kernel // Run the convolution for each feature variable typename CoordinateSystem<T>::GridPoint gridIter = gridpoint; vector<T> sum(value_rank, 0.0); size_t sumCount = 0; for (int i = minIndex; i < maxIndex; i++) { gridIter[fixedDimension] = i; // Again, make sure no points originally marked as // off limits are used #if SCALE_SPACE_SKIPS_NON_ORIGINAL_POINTS if (fs->off_limits()->get(gridpoint)) continue; #endif // get the point at the iterated position Point<T> *pIter = originalIndex->get(gridIter); if (pIter == NULL) continue; // apply the pre-sampled gaussian and sum up // in each variable in the feature-space size_t d = (i <= k) ? (k - i) : (i - k); for (int varIndex = 0; varIndex < value_rank; varIndex++) { T value = pIter->values[cs->rank() + varIndex]; sum[varIndex] += g.value(d) * value; } sumCount++; } // No muss, no fuss if (sumCount == 0) continue; // Fuss! Fetch the point from the array index Point<T> *p = filteredPoints->get(gridpoint); // If no point existed, decide if we need to create one if (p == NULL) { // Create a new point with default values // and insert into array index typename CoordinateSystem<T>::Coordinate coordinate = cs->newCoordinate(); cs->lookup(gridpoint, coordinate); vector<T> values = coordinate; values.resize(fs->rank(), 0.0); p = PointFactory<T>::get_instance()->create(gridpoint, coordinate, values); // Did this exist in the original index? Point<T> *op = originalIndex->get(gridpoint); p->isOriginalPoint = ((op == NULL) ? false : op->isOriginalPoint); // Since we just created this point, there // is no need to copy it again when adding // it to the array index #if WITH_OPENMP #pragma omp critical { #endif filteredPoints->set(gridpoint, p, false); #if WITH_OPENMP } #endif } // If we have a point after all that, update it with the // filtered value if (p != NULL) { // copy values and track limits for (int varIndex = 0; varIndex < value_rank; varIndex++) { p->values[numDims + varIndex] = sum[varIndex]; if (sum[varIndex] < m_min[varIndex]) { #if WITH_OPENMP #pragma omp critical #endif m_min[varIndex] = sum[varIndex]; } if (sum[varIndex] > m_max[varIndex]) { #if WITH_OPENMP #pragma omp critical #endif m_max[varIndex] = sum[varIndex]; } } } } } } template<typename T> void ScaleSpaceFilter<T>::apply_parallellized(FeatureSpace <T> *fs) { LinearIndexMapping mapping(fs->coordinate_system->get_dimension_sizes()); size_t N = mapping.size(); const size_t value_rank = fs->value_rank(); using namespace std; const CoordinateSystem<T> *cs = fs->coordinate_system; // index the original if (this->show_progress()) { cout << endl << "Constructing array indexes ..."; start_timer(); } ArrayIndex<T> *originalIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), fs->points, true); ArrayIndex<T> *filteredIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), false); if (this->show_progress()) { cout << "done. (" << stop_timer() << "s)" << endl; } if (this->show_progress()) { cout << endl << "Applying scale filter t=" << m_scale << " decay=" << m_decay << " ... " << endl; long numPoints = 1; for (size_t i = 0; i < fs->coordinate_system->rank(); i++) { numPoints *= fs->coordinate_system->dimensions()[i].getSize(); } m_progress_bar = new boost::progress_display(fs->spatial_rank() * numPoints); start_timer(); } // initialize min/max and re-set counts for (size_t varIndex = 0; varIndex < value_rank; varIndex++) { m_min[varIndex] = std::numeric_limits<T>::max(); m_max[varIndex] = std::numeric_limits<T>::min(); } // // Apply dimension by dimension (exploiting separability) // for (size_t dimIndex = 0; dimIndex < fs->spatial_rank(); dimIndex++) { apply_parallellized_on_dimension(fs, originalIndex, filteredIndex, dimIndex); delete originalIndex; if (dimIndex < (fs->spatial_rank() - 1)) { originalIndex = filteredIndex; filteredIndex = new ArrayIndex<T>(cs->get_dimension_sizes(), false); } } // replace the points in the original with the filtered // array index results filteredIndex->replace_points(fs->points); size_t originalPoints = 0; for (size_t i = 0; i < fs->points.size(); i++) { if (fs->points[i]->isOriginalPoint) originalPoints++; } if (this->show_progress()) { cout << "done. (" << stop_timer() << "s)" << endl; cout << "Filtered featurespace contains " << fs->size() << " points (" << originalPoints << " original points, " << "(" << (fs->size() - originalPoints) << " new points))" << endl; delete m_progress_bar; m_progress_bar = NULL; } // Clean up delete filteredIndex; } template<typename T> void ScaleSpaceFilter<T>::apply(FeatureSpace <T> *fs) { this->m_unfiltered_min = fs->min(); this->m_unfiltered_max = fs->max(); //this->applyWithArrayIndex(fs); this->apply_parallellized(fs); } #pragma mark - #pragma mark Range handling template<typename T> map<size_t, T> ScaleSpaceFilter<T>::getRangeFactors() { map<size_t, T> factors; typename map<size_t, T>::iterator mi; for (mi = m_min.begin(); mi != m_min.end(); mi++) { size_t i = mi->first; factors[i] = (m_max[i] - m_min[i]) / (m_unfiltered_max[i] - m_unfiltered_min[i]); } return factors; } template<typename T> const map<size_t, T> & ScaleSpaceFilter<T>::get_filtered_min() { return m_min; } template<typename T> const map<size_t, T> & ScaleSpaceFilter<T>::get_filtered_max() { return m_max; } } #endif
main2.h
#pragma once #include "geometrycentral/surface/halfedge_mesh.h" #include "geometrycentral/surface/meshio.h" #include "geometrycentral/surface/vertex_position_geometry.h" //#include <boost/program_options.hpp> //namespace po = boost::program_options; #include "../deps/polyscope/deps/args/args/args.hxx" #include <omp.h> #include <mkl.h> #include <mkl_spblas.h> //#include <tbb/task_scheduler_init.h> #include <memory> #include <Eigen/Core> #include "rsurface_types.h" #include "surface_flow.h" #include "remeshing/dynamic_remesher.h" #include "remeshing/remeshing.h" #include "scene_file.h" #include "bct_kernel_type.h" #include "optimized_bct.h" #include "bct_constructors.h" #include "helpers.h" #include "energy/all_energies.h" namespace rsurfaces { struct Benchmarker { mint max_thread_count = 1; mint thread_count = 1; mint thread_step = 1; mint burn_ins = 1; mint iterations = 3; mreal alpha = 6.; mreal beta = 12.; mreal theta = 0.5; mreal chi = 0.5; mreal weight = 1.; std::string obj1 = "../scenes/Bunny/bunny.obj"; std::string profile_name = "Profile"; std::string path = "."; TreePercolationAlgorithm tree_perc_alg = TreePercolationAlgorithm::Tasks; MeshPtr mesh1; GeomPtr geom1; std::shared_ptr<TPPointCloudObstacleBarnesHut0> tp_o_pc; std::shared_ptr<TPPointNormalCloudObstacleBarnesHut0> tp_o_pnc; Eigen::MatrixXd U; Eigen::MatrixXd V; mreal E_11; Eigen::MatrixXd DE_11; void Compute( mint iter ) { // OptimizedClusterTree *bvh1 = CreateOptimizedBVH(mesh1, geom1); print("BVH"); ptic("BVH"); auto tpe_bh_11 = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); ptoc("BVH"); tpe_bh_11->GetBVH()->settings.tree_perc_alg = tree_perc_alg; if( iter < 0) { tpe_bh_11->GetBVH()->PrintToFile( path + "/" + "OptimizedClusterTree.tsv"); } print("Energy"); ptic("Energy"); E_11 = tpe_bh_11->Value(); DE_11.setZero(); tpe_bh_11->Differential(DE_11); ptoc("Energy"); // MeshUPtr u_pc_mesh; // GeomUPtr u_pc_geom; // std::tie(u_pc_mesh, u_pc_geom) = readMesh("../scenes/LungGrowing/sphere.obj"); // // mint n = u_pc_mesh->nVertices(); // u_pc_geom->requireVertexNormals(); // // Eigen::MatrixXd pt_coords( n, 3); // Eigen::MatrixXd pt_normals( n, 3); // Eigen::VectorXd pt_weights( n); // // #pragma omp parallel for // for( mint i = 0; i < n; ++i ) // { // pt_weights(i) = 1.; // pt_coords(i, 0) = u_pc_geom->inputVertexPositions[i][0]; // pt_coords(i, 1) = u_pc_geom->inputVertexPositions[i][1]; // pt_coords(i, 2) = u_pc_geom->inputVertexPositions[i][2]; // pt_normals(i, 0) = u_pc_geom->vertexNormals[i][0]; // pt_normals(i, 1) = u_pc_geom->vertexNormals[i][1]; // pt_normals(i, 2) = u_pc_geom->vertexNormals[i][2]; // } // // // ptic("TPPointCloudObstacleBarnesHut0"); // // tp_o_pc = std::make_shared<TPPointCloudObstacleBarnesHut0>(mesh1, geom1, tpe_bh_11.get(), pt_weights, pt_coords, alpha, beta, theta, weight); // // E_11 = tp_o_pc->Value(); // DE_11.setZero(); // // tp_o_pc->Differential(DE_11); // ptoc("TPPointCloudObstacleBarnesHut0"); // // ptic("TPPointNormalCloundObstacleBarnesHut0"); // tp_o_pnc = std::make_shared<TPPointNormalCloudObstacleBarnesHut0>(mesh1, geom1, tpe_bh_11.get(), pt_weights, pt_coords, pt_normals, alpha, beta, theta, weight); // // E_11 = tp_o_pnc->Value(); // // DE_11.setZero(); // // tp_o_pnc->Differential(DE_11); // // ptoc("TPPointNormalCloundObstacleBarnesHut0"); std::shared_ptr<OptimizedBlockClusterTree> bct11; print("Multiply MKL CSR"); ptic("Multiply MKL CSR"); BCTSettings settings; settings.mult_alg = NearFieldMultiplicationAlgorithm::MKL_CSR; bct11 = std::make_shared<OptimizedBlockClusterTree>(tpe_bh_11->GetBVH(), tpe_bh_11->GetBVH(), alpha, beta, chi, weight, settings); for( mint k = 0; k < 20; ++k) { ptic("Multiply Fractional"); bct11->Multiply(V,U,BCTKernelType::FractionalOnly); ptoc("Multiply Fractional"); ptic("Multiply HighOrder"); bct11->Multiply(V,U,BCTKernelType::HighOrder); ptoc("Multiply HighOrder"); ptic("Multiply LowOrder"); bct11->Multiply(V,U,BCTKernelType::LowOrder); ptoc("Multiply LowOrder"); } ptoc("Multiply MKL CSR"); print("Multiply Hybrid"); ptic("Multiply Hybrid"); settings.mult_alg = NearFieldMultiplicationAlgorithm::Hybrid; bct11 = std::make_shared<OptimizedBlockClusterTree>(tpe_bh_11->GetBVH(), tpe_bh_11->GetBVH(), alpha, beta, chi, weight, settings); for( mint k = 0; k < 20; ++k) { ptic("Multiply Fractional"); bct11->Multiply(V,U,BCTKernelType::FractionalOnly); ptoc("Multiply Fractional"); ptic("Multiply HighOrder"); bct11->Multiply(V,U,BCTKernelType::HighOrder); ptoc("Multiply HighOrder"); ptic("Multiply LowOrder"); bct11->Multiply(V,U,BCTKernelType::LowOrder); ptoc("Multiply LowOrder"); } ptoc("Multiply Hybrid"); } void Prepare() { ptic("Vectors"); mint vertex_count1 = mesh1->nVertices(); DE_11 = Eigen::MatrixXd(vertex_count1, 3); V = getVertexPositions( mesh1, geom1 ); U = Eigen::MatrixXd(vertex_count1, 3); U.setZero(); ptoc("Vectors"); } void PrintStats() { std::cout << "mesh = "<< obj1 << std::endl; // std::cout << "profile_file = "<< profile_file << std::endl; std::cout << "threads = "<< thread_count << std::endl; std::cout << "alpha = "<< alpha << std::endl; std::cout << "beta = "<< beta << std::endl; std::cout << "theta = "<< theta << std::endl; std::cout << "chi = "<< chi << std::endl; } void TestMultiply() { auto tpe_bh_11 = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); tpe_bh_11->GetBVH()->PrintToFile( path + "/" + "OptimizedClusterTree.tsv"); // E_11 = tpe_bh_11->Value(); // DE_11.setZero(); // // tpe_bh_11->Differential(DE_11); ptic("Multiply"); auto bct11 = std::make_shared<OptimizedBlockClusterTree>(tpe_bh_11->GetBVH(), tpe_bh_11->GetBVH(), alpha, beta, chi, weight ); // for( mint k = 0; k < 20; ++k) // { // ptic("Multiply Fractional"); // bct11->Multiply(V,U,BCTKernelType::FractionalOnly); // ptoc("Multiply Fractional"); // // ptic("Multiply HighOrder"); // bct11->Multiply(V,U,BCTKernelType::HighOrder); // ptoc("Multiply HighOrder"); // // ptic("Multiply LowOrder"); // bct11->Multiply(V,U,BCTKernelType::LowOrder); // ptoc("Multiply LowOrder"); // } OptimizedClusterTree * S = bct11->S; OptimizedClusterTree * T = bct11->T; S->RequireBuffers(1); T->RequireBuffers(1); S->CleanseBuffers(); T->CleanseBuffers(); mint n = T->cluster_count; Eigen::VectorXd v ( n ); Eigen::VectorXd u0 ( n ); Eigen::VectorXd u1 ( n ); Eigen::VectorXd u2 ( n ); std::uniform_real_distribution<double> unif(-1.,1.); std::default_random_engine re; for( mint i = 0; i < n; ++i) { v(i) = unif(re); } T->RequireChunks(); print("\n################################"); print("PercolateUp"); T->CleanseBuffers(); std::copy( v.data(), v.data() + n, T->C_in ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Tasks; T->PercolateUp(); std::copy( T->C_in, T->C_in + n, u0.data() ); T->CleanseBuffers(); std::copy( v.data(), v.data() + n, T->C_in ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Sequential; T->PercolateUp(); std::copy( T->C_in, T->C_in + n, u1.data() ); T->CleanseBuffers(); std::copy( v.data(), v.data() +n, T->C_in ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Chunks; T->PercolateUp(); std::copy( T->C_in, T->C_in + n, u2.data() ); valprint("u0.norm()", u0.norm() ); valprint("Absolute error Tasks-Sequential", (u0-u1).norm() ); valprint("Relative error Tasks-Sequential", (u0-u1).norm()/u0.norm()); valprint("Absolute error Tasks-Chunks", (u2-u0).norm() ); valprint("Relative error Tasks-Chunks", (u2-u0).norm()/u0.norm() ); valprint("Absolute error Sequential-Chunks", (u2-u1).norm() ); valprint("Relative error Sequential-Chunks", (u2-u1).norm()/u1.norm() ); print("\n################################"); print("PercolateDown"); tic("Tasks"); T->CleanseBuffers(); std::copy( v.data(), v.data() + n, T->C_out ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Tasks; T->PercolateDown(); std::copy( T->C_out, T->C_out + n, u0.data() ); toc("Tasks"); tic("Sequential"); T->CleanseBuffers(); std::copy( v.data(), v.data() + n, T->C_out ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Sequential; T->PercolateDown(); std::copy( T->C_out, T->C_out + n, u1.data() ); toc("Sequential"); tic("Chunks"); T->CleanseBuffers(); std::copy( v.data(), v.data() + n, T->C_out ); T->settings.tree_perc_alg = TreePercolationAlgorithm::Chunks; T->PercolateDown(); std::copy( T->C_out, T->C_out + n, u2.data() ); toc("Chunks"); valprint("u0.norm()", u0.norm() ); valprint("Absolute error Tasks-Sequential", (u0-u1).norm() ); valprint("Relative error Tasks-Sequential", (u0-u1).norm()/u0.norm()); valprint("Absolute error Tasks-Chunks", (u2-u0).norm() ); valprint("Relative error Tasks-Chunks", (u2-u0).norm()/u0.norm() ); valprint("Absolute error Sequential-Chunks", (u2-u1).norm() ); valprint("Relative error Sequential-Chunks", (u2-u1).norm()/u1.norm() ); print("\n################################"); print("Full Multiply"); BCTKernelType type = BCTKernelType::LowOrder; mint m = T->primitive_count; mint cols = 3; S->RequireBuffers(cols); T->RequireBuffers(cols); Eigen::MatrixXd V ( m , cols ); Eigen::MatrixXd V0 ( m , cols ); for( mint i = 0; i < m; ++i) { for( mint j = 0; j < cols; ++ j) { V0(i,j) = V(i,j) = unif(re); } } // T->Pre( V, type ); Eigen::MatrixXd U0 ( m , cols ); U0.setZero(); T->CleanseBuffers(); S->CleanseBuffers(); bct11->S->settings.tree_perc_alg = TreePercolationAlgorithm::Tasks; bct11->Multiply(V,U0,type, false); Eigen::MatrixXd U1 ( m , cols ); U1.setZero(); T->CleanseBuffers(); S->CleanseBuffers(); bct11->S->settings.tree_perc_alg = TreePercolationAlgorithm::Sequential; bct11->Multiply(V,U1,type, false); Eigen::MatrixXd U2 ( m , cols ); U2.setZero(); T->CleanseBuffers(); S->CleanseBuffers(); bct11->S->settings.tree_perc_alg = TreePercolationAlgorithm::Chunks; bct11->Multiply(V,U2,type, false); valprint("(V-V0).norm()", (V-V0).norm() ); valprint("Absolute multiplication error Tasks-Sequential", (U0-U1).norm() ); valprint("Relative multiplication error Tasks-Sequential", (U0-U1).norm()/U0.norm() ); valprint("Absolute multiplication error Tasks-Chunks", (U2-U0).norm() ); valprint("Relative multiplication error Tasks-Chunks", (U2-U0).norm()/U0.norm() ); valprint("Absolute multiplication error Sequential-Chunks", (U2-U1).norm() ); valprint("Relative multiplication error Sequential-Chunks", (U2-U1).norm()/U1.norm() ); ptoc("Multiply"); } // void TestMKLOptimize() // { // auto tpe_bh_11 = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); // // // auto bct11 = std::make_shared<OptimizedBlockClusterTree>(tpe_bh_11->GetBVH(), tpe_bh_11->GetBVH(), alpha, beta, chi, weight); // // // // mint m = bct11->near->m; // mint n = bct11->near->n; // mint cols = 9; // mreal * values = bct11->near->hi_values; // mreal factor = 1.; // // // Eigen::VectorXd v ( n * cols ); // std::uniform_real_distribution<double> unif(-1.,1.); // std::default_random_engine re; // // for( mint i = 0; i < n * cols; ++i) // { // v(i) = unif(re); // } // // Eigen::VectorXd u1 ( n * cols ); // Eigen::VectorXd u2 ( n * cols ); // // sparse_matrix_t A = NULL; // sparse_status_t stat = mkl_sparse_d_create_csr ( &A, SPARSE_INDEX_BASE_ZERO, m, n, bct11->near->OuterPtrB(), bct11->near->OuterPtrE(), bct11->near->InnerPtr(), values ); // if (stat) // { // eprint("mkl_sparse_d_create_csr returned stat = " + std::to_string(stat) ); // } // // mint repetitions = 20; // // tic("MKL_CSR unoptimized"); // for( mint i = 0; i < repetitions; ++i ) // { // stat = mkl_sparse_d_mm ( SPARSE_OPERATION_NON_TRANSPOSE, factor, A, bct11->near->descr, SPARSE_LAYOUT_ROW_MAJOR, v.data(), cols, cols, 0., u1.data(), cols ); // if (stat) // { // eprint("mkl_sparse_d_mm returned stat = " + std::to_string(stat) ); // } // } // toc("MKL_CSR unoptimized"); // // tic("optimization"); // stat = mkl_sparse_set_mm_hint(A, SPARSE_OPERATION_NON_TRANSPOSE, bct11->near->descr, SPARSE_LAYOUT_ROW_MAJOR, cols, 100 * repetitions); // if (stat) // { // eprint("mkl_sparse_set_mm_hint returned stat = " + std::to_string(stat) ); // } // // stat = mkl_sparse_optimize( A ); // if (stat) // { // eprint("mkl_sparse_optimize = " + std::to_string(stat) ); // } // toc("optimization"); // // tic("MKL_CSR optimized"); // for( mint i = 0; i < repetitions; ++i ) // { // stat = mkl_sparse_d_mm ( SPARSE_OPERATION_NON_TRANSPOSE, factor, A, bct11->near->descr, SPARSE_LAYOUT_ROW_MAJOR, v.data(), cols, cols, 0., u2.data(), cols ); // if (stat) // { // eprint("mkl_sparse_d_mm returned stat = " + std::to_string(stat) ); // } // } // toc("MKL_CSR optimized"); // // // valprint("(u1-u2).norm()",(u1-u2).norm()); // valprint("(u1-u2).norm()/u1.norm()",(u1-u2).norm()/u1.norm()); // // } // void TestMKLOptimize() // { // auto tpe_bh_11 = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); // // // auto bct11 = std::make_shared<OptimizedBlockClusterTree>(tpe_bh_11->GetBVH(), tpe_bh_11->GetBVH(), alpha, beta, chi, weight); // // // MKLSparseMatrix matrix = bct11->S->P_to_C; // // mint m = matrix.m; // mint n = matrix.n; // mint cols = 9; // // mreal factor = 1.; // // // Eigen::VectorXd v ( n * cols ); // std::uniform_real_distribution<double> unif(-1.,1.); // std::default_random_engine re; // // for( mint i = 0; i < n * cols; ++i) // { // v(i) = unif(re); // } // // Eigen::VectorXd u1 ( m * cols ); // Eigen::VectorXd u2 ( m * cols ); // // // // sparse_matrix_t A = NULL; // sparse_status_t stat = mkl_sparse_d_create_csr ( &A, SPARSE_INDEX_BASE_ZERO, m, n, matrix.outer, matrix.outer + 1 , matrix.inner, matrix.values ); // if (stat) // { // eprint("mkl_sparse_d_create_csr returned stat = " + std::to_string(stat) ); // } // // mint repetitions = 20; // // tic("MKL_CSR unoptimized"); // for( mint i = 0; i < repetitions; ++i ) // { // stat = mkl_sparse_d_mm ( SPARSE_OPERATION_NON_TRANSPOSE, factor, A, matrix.descr, SPARSE_LAYOUT_ROW_MAJOR, v.data(), cols, cols, 0., u1.data(), cols ); // if (stat) // { // eprint("mkl_sparse_d_mm returned stat = " + std::to_string(stat) ); // } // } // toc("MKL_CSR unoptimized"); // // tic("optimization"); // stat = mkl_sparse_set_mm_hint(A, SPARSE_OPERATION_NON_TRANSPOSE, matrix.descr, SPARSE_LAYOUT_ROW_MAJOR, cols, 100 * repetitions); // if (stat) // { // eprint("mkl_sparse_set_mm_hint returned stat = " + std::to_string(stat) ); // } // // stat = mkl_sparse_optimize( A ); // if (stat) // { // eprint("mkl_sparse_optimize = " + std::to_string(stat) ); // } // toc("optimization"); // // tic("MKL_CSR optimized"); // for( mint i = 0; i < repetitions; ++i ) // { // stat = mkl_sparse_d_mm ( SPARSE_OPERATION_NON_TRANSPOSE, factor, A, matrix.descr, SPARSE_LAYOUT_ROW_MAJOR, v.data(), cols, cols, 0., u2.data(), cols ); // if (stat) // { // eprint("mkl_sparse_d_mm returned stat = " + std::to_string(stat) ); // } // } // toc("MKL_CSR optimized"); // // // valprint("(u1-u2).norm()",(u1-u2).norm()); // valprint("(u1-u2).norm()/u1.norm()",(u1-u2).norm()/u1.norm()); // // } // void TestVBSR() // { // // omp_set_num_threads(1); // mkl_set_num_threads(1); // // auto tpe = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); // // auto bct = std::make_shared<OptimizedBlockClusterTree>(tpe->GetBVH(), tpe->GetBVH(), alpha, beta, chi, weight); // // mint n = bct->near->n; // mint m = bct->near->m; // mint cols = 9; // // Eigen::VectorXd v ( n * cols ); // Eigen::VectorXd u1 ( m * cols ); // Eigen::VectorXd u2 ( m * cols ); // Eigen::VectorXd u3 ( m * cols ); // // std::uniform_real_distribution<double> unif(-1.,1.); // std::default_random_engine re; // for( mint i = 0; i < n * cols; ++i) // { // v(i) = unif(re); // } // // tic("ApplyKernel_CSR_MKL"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_CSR_MKL( bct->near->hi_values, v.data(), u1.data(), cols, 1. ); // } // toc("ApplyKernel_CSR_MKL"); // // tic("ApplyKernel_VBSR"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_VBSR( bct->near->hi_values, v.data(), u2.data(), cols, 1. ); // } // toc("ApplyKernel_VBSR"); // // tic("ApplyKernel_Hybrid"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_Hybrid( bct->near->hi_values, v.data(), u3.data(), cols, 1. ); // } // toc("ApplyKernel_Hybrid"); // // // // omp_set_num_threads(4); // mkl_set_num_threads(4); // // tpe = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); // // bct = std::make_shared<OptimizedBlockClusterTree>(tpe->GetBVH(), tpe->GetBVH(), alpha, beta, chi, weight); // // for( mint i = 0; i < n * cols; ++i) // { // v(i) = unif(re); // } // // tic("ApplyKernel_CSR_MKL"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_CSR_MKL( bct->near->hi_values, v.data(), u1.data(), cols, 1. ); // } // toc("ApplyKernel_CSR_MKL"); // // tic("ApplyKernel_VBSR"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_VBSR( bct->near->hi_values, v.data(), u2.data(), cols, 1. ); // } // toc("ApplyKernel_VBSR"); // // tic("ApplyKernel_Hybrid"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_Hybrid( bct->near->hi_values, v.data(), u3.data(), cols, 1. ); // } // toc("ApplyKernel_Hybrid"); // // // omp_set_num_threads(max_thread_count); // mkl_set_num_threads(max_thread_count); // // tpe = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); // // bct = std::make_shared<OptimizedBlockClusterTree>(tpe->GetBVH(), tpe->GetBVH(), alpha, beta, chi, weight); // // for( mint i = 0; i < n * cols; ++i) // { // v(i) = unif(re); // } // // tic("ApplyKernel_CSR_MKL"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_CSR_MKL( bct->near->hi_values, v.data(), u1.data(), cols, 1. ); // } // toc("ApplyKernel_CSR_MKL"); // // tic("ApplyKernel_VBSR"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_VBSR( bct->near->hi_values, v.data(), u2.data(), cols, 1. ); // } // toc("ApplyKernel_VBSR"); // // tic("ApplyKernel_Hybrid"); // for( mint i = 0; i < 20; ++i) // { // bct->near->ApplyKernel_Hybrid( bct->near->hi_values, v.data(), u3.data(), cols, 1. ); // } // toc("ApplyKernel_Hybrid"); // //// valprint("(u1-u2).norm()/u1.norm()",(u1-u2).norm()/u1.norm()); //// valprint("(u1-u3).norm()/u1.norm()",(u1-u2).norm()/u1.norm()); // } void TestHybrid() { mint repetitions = 20; mint cols = 9; omp_set_num_threads(1); mkl_set_num_threads(1); std::shared_ptr<TPEnergyBarnesHut0> tpe; std::shared_ptr<OptimizedBlockClusterTree> bct; tpe = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); bct = std::make_shared<OptimizedBlockClusterTree>(tpe->GetBVH(), tpe->GetBVH(), alpha, beta, chi, weight); mint n = bct->near->n; mint m = bct->near->m; mreal * v = nullptr; mreal * u1_1 = nullptr; mreal * u1_2 = nullptr; mreal * u2_1 = nullptr; mreal * u2_2 = nullptr; safe_alloc( v, n * cols, 0.); safe_alloc( u1_1, m * cols, 0.); safe_alloc( u1_2, m * cols, 0.); safe_alloc( u2_1, m * cols, 0.); safe_alloc( u2_2, m * cols, 0.); Eigen::Map<Eigen::VectorXd> V ( v, n * cols ); Eigen::Map<Eigen::VectorXd> U1_1 ( u1_1, m * cols ); Eigen::Map<Eigen::VectorXd> U1_2 ( u1_2, m * cols ); Eigen::Map<Eigen::VectorXd> U2_1 ( u2_1, m * cols ); Eigen::Map<Eigen::VectorXd> U2_2 ( u2_2, m * cols ); std::uniform_real_distribution<double> unif(-1.,1.); std::default_random_engine re; re.seed(std::chrono::system_clock::now().time_since_epoch().count()); for( mint i = 0; i < n * cols; ++i) { v[i] = unif(re); } valprint("u1_1.norm()", U1_1.norm()); valprint("u1_2.norm()", U1_2.norm()); tic("ApplyKernel_CSR_MKL"); for( mint i = 0; i < repetitions; ++i) { bct->near->ApplyKernel_CSR_MKL( bct->near->hi_values, v, u1_1, cols, 1. ); } toc("ApplyKernel_CSR_MKL"); tic("ApplyKernel_Hybrid"); for( mint i = 0; i < repetitions; ++i) { bct->near->ApplyKernel_Hybrid( bct->near->hi_values, v, u1_2, cols, 1. ); } toc("ApplyKernel_Hybrid"); valprint("u1_1.norm()", U1_1.norm()); valprint("u1_2.norm()", U1_2.norm()); valprint("(u1_1-u1_2).norm()/u1_1.norm()",(U1_1-U1_2).norm()/U1_1.norm()); omp_set_num_threads(max_thread_count); mkl_set_num_threads(max_thread_count); tpe = std::make_shared<TPEnergyBarnesHut0>(mesh1, geom1, alpha, beta, theta, weight); bct = std::make_shared<OptimizedBlockClusterTree>(tpe->GetBVH(), tpe->GetBVH(), alpha, beta, chi, weight); valprint("u2_1.norm()", U2_1.norm()); valprint("u2_2.norm()", U2_2.norm()); tic("ApplyKernel_CSR_MKL"); for( mint i = 0; i < repetitions; ++i) { bct->near->ApplyKernel_CSR_MKL( bct->near->hi_values, v, u2_1, cols, 1. ); } toc("ApplyKernel_CSR_MKL"); tic("ApplyKernel_Hybrid"); for( mint i = 0; i < repetitions; ++i) { bct->near->ApplyKernel_Hybrid( bct->near->hi_values, v, u2_2, cols, 1. ); } toc("ApplyKernel_Hybrid"); valprint("u2_1.norm()", U2_1.norm()); valprint("u2_2.norm()", U2_2.norm()); valprint("(u2_1-u2_2).norm()/u1_2.norm()",(U2_1-U2_2).norm()/U2_1.norm()); safe_free(v); safe_free(u1_1); safe_free(u1_2); safe_free(u2_1); safe_free(u2_2); } // void TestPrePost() // { //// OptimizedClusterTreeOptions::tree_perc_alg = TreePercolationAlgorithm::Sequential; // //// auto type = BCTKernelType::HighOrder; // auto type = BCTKernelType::LowOrder; // // // // std::vector<BCTKernelType> types { BCTKernelType::FractionalOnly, BCTKernelType::LowOrder, BCTKernelType::HighOrder }; // // std::uniform_real_distribution<double> unif(-1.,1.); // std::default_random_engine re; // re.seed(std::chrono::system_clock::now().time_since_epoch().count()); // // // mint repetitions = 1; // mint cols = 3; // // omp_set_num_threads(4); // mkl_set_num_threads(4); // // // for( auto type : types) // { //// OptimizedClusterTreeOptions::use_old_prepost = true; // auto * bvh_old = CreateOptimizedBVH(mesh1, geom1); // bvh_old->CleanseBuffers(); // //// OptimizedClusterTreeOptions::use_old_prepost = false; // auto * bvh_new = CreateOptimizedBVH(mesh1, geom1); // bvh_new->CleanseBuffers(); // // mint n = mesh1->nVertices(); // mint m = bvh_old->cluster_count; // // Eigen::MatrixXd V ( n , cols ); // for( mint i = 0; i < n; ++i) // { // for( mint j = 0; j < cols; ++j) // { // V(i,j) = unif(re); // } // } // Eigen::MatrixXd V0 = V; // // valprint("V.norm()", V.norm()); // // tic("Old"); // for( mint i = 0; i < repetitions; ++i) // { // bvh_old->Pre( V, type); // } // toc("Old"); // valprint("(V0-V).norm()/V0.norm()",(V0-V).norm()/V0.norm()); // valprint("bvh_old->buffer_dim",bvh_old->buffer_dim); // Eigen::Map<Eigen::MatrixXd> U1 ( bvh_old->P_in, n, bvh_old->buffer_dim ); // Eigen::Map<Eigen::MatrixXd> W1 ( bvh_old->C_in, m, bvh_old->buffer_dim ); // // tic("New"); // for( mint i = 0; i < repetitions; ++i) // { // bvh_new->Pre( V, type); // } // toc("New"); // valprint("(V0-V).norm()/V0.norm()",(V0-V).norm()/V0.norm()); // valprint("bvh_new->buffer_dim",bvh_new->buffer_dim); // Eigen::Map<Eigen::MatrixXd> U2 ( bvh_new->P_in, n, bvh_new->buffer_dim ); // Eigen::Map<Eigen::MatrixXd> W2 ( bvh_new->C_in, m, bvh_new->buffer_dim ); // // valprint("U1.norm()", U1.norm()); // valprint("U2.norm()", U2.norm()); // valprint("(U1-U2).norm()/U1.norm()",(U1-U2).norm()/U1.norm()); // valprint("W1.norm()", W1.norm()); // valprint("W2.norm()", W2.norm()); // valprint("(W1-W2).norm()/W1.norm()",(W1-W2).norm()/W1.norm()); // // // delete bvh_old; // delete bvh_new; // } // } void TestBatch() { ptic("TestBatch"); auto tpe_bh = std::make_shared<TPEnergyBarnesHut0>( mesh1, geom1, alpha, beta, theta, weight ); tpe_bh->GetBVH()->PrintToFile( path + "/" + "OptimizedClusterTree.tsv"); BCTSettings settings; settings.mult_alg = NearFieldMultiplicationAlgorithm::Hybrid; // settings.mult_alg = NearFieldMultiplicationAlgorithm::MKL_CSR; auto bct = std::make_shared<OptimizedBlockClusterTree>( tpe_bh->GetBVH(), tpe_bh->GetBVH(), alpha, beta, chi, weight, settings ); mint n = mesh1->nVertices(); mint k = 3; mint mult = 3; mint kk = k * mult; Eigen::MatrixXd VV( n , kk ); Eigen::MatrixXd WW( n , kk ); Eigen::MatrixXd V ( n , k ); Eigen::MatrixXd W ( n , k ); WW.setZero(); W.setZero(); std::uniform_real_distribution<double> unif(-1.,1.); std::default_random_engine re; for( mint i = 0; i < n; ++i) { for( mint j = 0; j < kk; ++j) { VV(i,j) = unif(re); } } for( mint i = 0; i < n; ++i) { for( mint j = 0; j < k; ++j) { V(i,j) = unif(re); } } print("Batch"); ptic("Batch"); for( mint i = 0; i < iterations; ++i ) { bct->Multiply( VV, WW, BCTKernelType::FractionalOnly ); bct->Multiply( VV, WW, BCTKernelType::LowOrder ); bct->Multiply( VV, WW, BCTKernelType::HighOrder ); } ptoc("Batch"); valprint("bct->S->buffer_size",bct->S->buffer_dim); print("Single"); ptic("Single"); for( mint i = 0; i < iterations * mult; ++i ) { bct->Multiply( V, W, BCTKernelType::FractionalOnly ); bct->Multiply( V, W, BCTKernelType::LowOrder ); bct->Multiply( V, W, BCTKernelType::HighOrder ); } ptoc("Single"); valprint("bct->S->buffer_size",bct->S->buffer_dim); ptoc("TestBatch"); } }; // Benchmarker } // namespace rsurfaces
convolution_5x5.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 conv5x5s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*25 + q*25; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* r4 = img0 + w*4; const float* r5 = img0 + w*5; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k4567 = vld1q_f32(kernel0+4); float32x4_t _k891011 = vld1q_f32(kernel0+8); float32x4_t _k12131415 = vld1q_f32(kernel0+12); float32x4_t _k16171819 = vld1q_f32(kernel0+16); float32x4_t _k20212223 = vld1q_f32(kernel0+20); float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( // v11 = rx1 / rx3 // v12 = rx2 // v13 v14 = intermediate sum register "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n"// v7 = out "0: \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v8.4s}, [%2] \n"// v8 = out2 // r1 "prfm pldl1keep, [%4, #256] \n" "ld1 {v9.4s, v10.4s}, [%4] \n"// v9 v10 = r10 r14 "add %4, %4, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r11 "fmul v13.4s, v9.4s, %19.s[1] \n" "fmla v8.4s, v9.4s, %18.s[0] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r12 "fmla v7.4s, v11.4s, %19.s[2] \n" "fmul v14.4s, v11.4s, %18.s[1] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r13 "fmla v13.4s, v12.4s, %19.s[3] \n" "fmla v8.4s, v12.4s, %18.s[2] \n" "fmla v7.4s, v11.4s, %20.s[0] \n" "fmla v14.4s, v11.4s, %18.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v13.4s, v10.4s, %20.s[1] \n" "fmla v8.4s, v10.4s, %19.s[0] \n" // r2 "ld1 {v9.4s, v10.4s}, [%5] \n"// v9 v10 = r20 r24 "add %5, %5, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r21 "fmla v7.4s, v9.4s, %20.s[2] \n" "fmla v14.4s, v9.4s, %19.s[1] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r22 "fmla v13.4s, v11.4s, %20.s[3] \n" "fmla v8.4s, v11.4s, %19.s[2] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r23 "fmla v7.4s, v12.4s, %21.s[0] \n" "fmla v14.4s, v12.4s, %19.s[3] \n" "fmla v13.4s, v11.4s, %21.s[1] \n" "fmla v8.4s, v11.4s, %20.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v7.4s, v10.4s, %21.s[2] \n" "fmla v14.4s, v10.4s, %20.s[1] \n" // r3 "ld1 {v9.4s, v10.4s}, [%6] \n"// v9 v10 = r30 r34 "add %6, %6, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r31 "fmla v13.4s, v9.4s, %21.s[3] \n" "fmla v8.4s, v9.4s, %20.s[2] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r32 "fmla v7.4s, v11.4s, %22.s[0] \n" "fmla v14.4s, v11.4s, %20.s[3] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r33 "fmla v13.4s, v12.4s, %22.s[1] \n" "fmla v8.4s, v12.4s, %21.s[0] \n" "fmla v7.4s, v11.4s, %22.s[2] \n" "fmla v14.4s, v11.4s, %21.s[1] \n" "prfm pldl1keep, [%7, #256] \n" "fmla v13.4s, v10.4s, %22.s[3] \n" "fmla v8.4s, v10.4s, %21.s[2] \n" // r4 "ld1 {v9.4s, v10.4s}, [%7] \n"// v9 v10 = r40 r44 "add %7, %7, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r41 "fmla v7.4s, v9.4s, %23.s[0] \n" "fmla v14.4s, v9.4s, %21.s[3] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r41 "fmla v13.4s, v11.4s, %23.s[1] \n" "fmla v8.4s, v11.4s, %22.s[0] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r41 "fmla v7.4s, v12.4s, %23.s[2] \n" "fmla v14.4s, v12.4s, %22.s[1] \n" "fmla v13.4s, v11.4s, %23.s[3] \n" "fmla v8.4s, v11.4s, %22.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "fmla v7.4s, v10.4s, %24.s[0] \n" "fmla v14.4s, v10.4s, %22.s[3] \n" // r0 and r5 "ld1 {v9.4s, v10.4s}, [%3] \n"// v9 v10 = r00 r04 "add %3, %3, #16 \n" "ext v11.16b, v9.16b, v10.16b, #4 \n" //r01 "fmla v13.4s, v11.4s, %18.s[1] \n" "ext v12.16b, v9.16b, v10.16b, #8 \n" //r02 "fmla v7.4s, v12.4s, %18.s[2] \n" "ext v11.16b, v9.16b, v10.16b, #12 \n" //r03 "prfm pldl1keep, [%8, #256] \n" "fmla v13.4s, v11.4s, %18.s[3] \n" // r5 "ld1 {v11.4s, v12.4s}, [%8] \n"// v11 v12 = r50 r54 "add %8, %8, #16 \n" "fmla v8.4s, v11.4s, %23.s[0] \n" "fmla v14.4s, v12.4s, %24.s[0] \n" "fmla v7.4s, v9.4s, %18.s[0] \n" "fmla v13.4s, v10.4s, %19.s[0] \n" "ext v9.16b, v11.16b, v12.16b, #4 \n" //r51 "ext v10.16b, v11.16b, v12.16b, #8 \n" //r52 "fmla v14.4s, v9.4s, %23.s[1] \n" "ext v9.16b, v11.16b, v12.16b, #12 \n" //r53 "fmla v8.4s, v10.4s, %23.s[2] \n" "fmla v14.4s, v9.4s, %23.s[3] \n" "fadd v7.4s, v7.4s, v13.4s \n" "st1 {v7.4s}, [%1], #16 \n" "fadd v8.4s, v8.4s, v14.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v7.4s}, [%1] \n"// v7 = out "st1 {v8.4s}, [%2], #16 \n" "subs %w0, %w0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3), // %6 "=r"(r4), // %7 "=r"(r5) // %8 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "7"(r4), "8"(r5), "w"(_k0123), // %18 "w"(_k4567), // %19 "w"(_k891011), // %20 "w"(_k12131415), // %21 "w"(_k16171819), // %22 "w"(_k20212223), // %23 "w"(_k24242424) // %24 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q13, q13 \n" // "veor q14, q14 \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = out "0: \n" // q11 = rx1 / rx3 // q12 = rx2 // q13 q14 = intermediate sum register "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// q8 = out2 "pld [%4, #256] \n" // r1 "vld1.f32 {d18-d21}, [%4] \n"// q9 q10 = r10 r14 "add %4, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r11 "vmul.f32 q13, q9, %e19[1] \n" "vmla.f32 q8, q9, %e18[0] \n" "vext.32 q12, q9, q10, #2 \n"// r12 "vmla.f32 q7, q11, %f19[0] \n" "vmul.f32 q14, q11, %e18[1] \n" "vext.32 q11, q9, q10, #3 \n"// r13 "vmla.f32 q13, q12, %f19[1] \n" "vmla.f32 q8, q12, %f18[0] \n" "vmla.f32 q7, q11, %e20[0] \n" "vmla.f32 q14, q11, %f18[1] \n" "pld [%5, #256] \n" "vmla.f32 q13, q10, %e20[1] \n" "vmla.f32 q8, q10, %e19[0] \n" // r2 "vld1.f32 {d18-d21}, [%5] \n"// q9 q10 = r20 r24 "add %5, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r21 "vmla.f32 q7, q9, %f20[0] \n" "vmla.f32 q14, q9, %e19[1] \n" "vext.32 q12, q9, q10, #2 \n"// r22 "vmla.f32 q13, q11, %f20[1] \n" "vmla.f32 q8, q11, %f19[0] \n" "vext.32 q11, q9, q10, #3 \n"// r23 "vmla.f32 q7, q12, %e21[0] \n" "vmla.f32 q14, q12, %f19[1] \n" "vmla.f32 q13, q11, %e21[1] \n" "vmla.f32 q8, q11, %e20[0] \n" "pld [%6, #256] \n" "vmla.f32 q7, q10, %f21[0] \n" "vmla.f32 q14, q10, %e20[1] \n" // r3 "vld1.f32 {d18-d21}, [%6] \n"// q9 q10 = r30 r34 "add %6, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r31 "vmla.f32 q13, q9, %f21[1] \n" "vmla.f32 q8, q9, %f20[0] \n" "vext.32 q12, q9, q10, #2 \n"// r32 "vmla.f32 q7, q11, %e22[0] \n" "vmla.f32 q14, q11, %f20[1] \n" "vext.32 q11, q9, q10, #3 \n"// r33 "vmla.f32 q13, q12, %e22[1] \n" "vmla.f32 q8, q12, %e21[0] \n" "vmla.f32 q7, q11, %f22[0] \n" "vmla.f32 q14, q11, %e21[1] \n" "pld [%7, #256] \n" "vmla.f32 q13, q10, %f22[1] \n" "vmla.f32 q8, q10, %f21[0] \n" // r4 "vld1.f32 {d18-d21}, [%7] \n"// q9 q10 = r40 r44 "add %7, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r41 "vmla.f32 q7, q9, %e23[0] \n" "vmla.f32 q14, q9, %f21[1] \n" "vext.32 q12, q9, q10, #2 \n"// r42 "vmla.f32 q13, q11, %e23[1] \n" "vmla.f32 q8, q11, %e22[0] \n" "vext.32 q11, q9, q10, #3 \n"// r43 "vmla.f32 q7, q12, %f23[0] \n" "vmla.f32 q14, q12, %e22[1] \n" "vmla.f32 q13, q11, %f23[1] \n" "vmla.f32 q8, q11, %f22[0] \n" "pld [%3, #256] \n" "vmla.f32 q7, q10, %e24[0] \n" "vmla.f32 q14, q10, %f22[1] \n" // r0 and r5 "vld1.f32 {d18-d21}, [%3] \n"// q9 q10 = r00 r04 "add %3, #16 \n" "vext.32 q11, q9, q10, #1 \n"// r01 "vmla.f32 q13, q11, %e18[1] \n" "vext.32 q12, q9, q10, #2 \n"// r02 "vmla.f32 q7, q12, %f18[0] \n" "vext.32 q11, q9, q10, #3 \n"// r03 "pld [%8, #256] \n" "vmla.f32 q13, q11, %f18[1] \n" // r5 "vld1.f32 {d22-d25}, [%8] \n"// q11 q12 = r50 r54 "add %8, #16 \n" "vmla.f32 q8, q11, %e23[0] \n" "vmla.f32 q14, q12, %e24[0] \n" "vmla.f32 q7, q9, %e18[0] \n" "vmla.f32 q13, q10, %e19[0] \n" "vext.32 q9, q11, q12, #1 \n"// r51 "vext.32 q10, q11, q12, #2 \n"// r52 "vmla.f32 q14, q9, %e23[1] \n" "vext.32 q9, q11, q12, #3 \n"// r53 "vmla.f32 q8, q10, %f23[0] \n" "vmla.f32 q14, q9, %f23[1] \n" "vadd.f32 q7, q7, q13 \n" // "veor q13, q13 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vadd.f32 q8, q8, q14 \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = out // "veor q14, q14 \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3), // %6 "=r"(r4), // %7 "=r"(r5) // %8 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "7"(r4), "8"(r5), "w"(_k0123), // %18 "w"(_k4567), // %19 "w"(_k891011), // %20 "w"(_k12131415), // %21 "w"(_k16171819), // %22 "w"(_k20212223), // %23 "w"(_k24242424) // %24 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; float sum2 = 0; #if __ARM_NEON float32x4_t _r1 = vld1q_f32(r1); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _sum = vmulq_f32(_r1, _k1); float32x4_t _sum2 = vmulq_f32(_r1, _k0123); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _k2 = vld1q_f32(k2); _sum = vmlaq_f32(_sum, _r2, _k2); _sum2 = vmlaq_f32(_sum2, _r2, _k1); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k3 = vld1q_f32(k3); _sum = vmlaq_f32(_sum, _r3, _k3); _sum2 = vmlaq_f32(_sum2, _r3, _k2); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); _sum2 = vmlaq_f32(_sum2, _r4, _k3); float32x4_t _r0 = vld1q_f32(r0); _sum = vmlaq_f32(_sum, _r0, _k0123); float32x4_t _r5 = vld1q_f32(r5); _sum2 = vmlaq_f32(_sum2, _r5, _k20212223); float32x4_t _k_t4; _k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0); _k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1); _k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2); _k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3); float32x4_t _r_t4; _r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0); _r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1); _r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2); _r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3); _sum = vmlaq_f32(_sum, _r_t4, _k_t4); sum = r4[4] * k4[4]; _r_t4 = vextq_f32(_r_t4, _r_t4, 1); _r_t4 = vsetq_lane_f32(r4[4], _r_t4, 3); _sum2 = vmlaq_f32(_sum2, _r_t4, _k_t4); sum2 = r5[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _ss_ss2 = vpadd_f32(_ss, _ss2); sum += vget_lane_f32(_ss_ss2, 0); sum2 += vget_lane_f32(_ss_ss2, 1); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r1[3] * k0[3]; sum2 += r1[4] * k0[4]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r2[3] * k1[3]; sum2 += r2[4] * k1[4]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; sum2 += r3[3] * k2[3]; sum2 += r3[4] * k2[4]; sum2 += r4[0] * k3[0]; sum2 += r4[1] * k3[1]; sum2 += r4[2] * k3[2]; sum2 += r4[3] * k3[3]; sum2 += r4[4] * k3[4]; sum2 += r5[0] * k4[0]; sum2 += r5[1] * k4[1]; sum2 += r5[2] * k4[2]; sum2 += r5[3] * k4[3]; sum2 += r5[4] * k4[4]; #endif // __ARM_NEON *outptr += sum; *outptr2 += sum2; r0++; r1++; r2++; r3++; r4++; r5++; outptr++; outptr2++; } r0 += 4 + w; r1 += 4 + w; r2 += 4 + w; r3 += 4 + w; r4 += 4 + w; r5 += 4 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%1, #128] \n" "prfm pldl1keep, [%2, #256] \n" "ld1 {v8.4s, v9.4s}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, %2, #16 \n" "0: \n" "ld1 {v7.4s}, [%1] \n"// _sum = vld1q_f32(outptr+j); "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r01 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r02 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r03 "fmla v7.4s, v8.4s, %14.s[0] \n" "fmul v13.4s, v10.4s, %14.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "fmul v14.4s, v11.4s, %14.s[2] \n" "fmul v15.4s, v12.4s, %14.s[3] \n" "fmla v7.4s, v9.4s, %15.s[0] \n" "ld1 {v8.4s, v9.4s}, [%3] \n" "add %3, %3, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r11 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r12 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r13 "fmla v7.4s, v8.4s, %15.s[1] \n" "fmla v13.4s, v10.4s, %15.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "fmla v14.4s, v11.4s, %15.s[3] \n" "fmla v15.4s, v12.4s, %16.s[0] \n" "fmla v7.4s, v9.4s, %16.s[1] \n" "ld1 {v8.4s, v9.4s}, [%4] \n" "add %4, %4, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r21 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r22 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r23 "fmla v7.4s, v8.4s, %16.s[2] \n" "fmla v13.4s, v10.4s, %16.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v14.4s, v11.4s, %17.s[0] \n" "fmla v15.4s, v12.4s, %17.s[1] \n" "fmla v7.4s, v9.4s, %17.s[2] \n" "ld1 {v8.4s, v9.4s}, [%5] \n" "add %5, %5, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r31 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r32 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r33 "fmla v7.4s, v8.4s, %17.s[3] \n" "fmla v13.4s, v10.4s, %18.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v14.4s, v11.4s, %18.s[1] \n" "fmla v15.4s, v12.4s, %18.s[2] \n" "fmla v7.4s, v9.4s, %18.s[3] \n" "ld1 {v8.4s, v9.4s}, [%6] \n" "add %6, %6, #16 \n" "ext v10.16b, v8.16b, v9.16b, #4 \n" //_r41 "ext v11.16b, v8.16b, v9.16b, #8 \n" //_r42 "ext v12.16b, v8.16b, v9.16b, #12 \n" //_r43 "fmla v7.4s, v8.4s, %19.s[0] \n" "fmla v13.4s, v10.4s, %19.s[1] \n" "fmla v14.4s, v11.4s, %19.s[2] \n" "fmla v15.4s, v12.4s, %19.s[3] \n" "fmla v7.4s, v9.4s, %20.s[0] \n" "fadd v14.4s, v14.4s, v15.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "prfm pldl1keep, [%2, #256] \n" "fadd v7.4s, v7.4s, v14.4s \n" "ld1 {v8.4s, v9.4s}, [%2] \n" "add %2, %2, #16 \n" "st1 {v7.4s}, [%1], #16 \n" "prfm pldl1keep, [%1, #128] \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %2, %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q15, q15 \n"// _sum3 = 0; "pld [%1, #128] \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, #16 \n" "0: \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum = vld1q_f32(outptr+j); // "veor q13, q13 \n"// _sum2 = 0; // "veor q14, q14 \n"// _sum3 = 0; "vext.32 q10, q8, q9, #1 \n"// _r01 "vext.32 q11, q8, q9, #2 \n"// _r02 "vext.32 q12, q8, q9, #3 \n"// _r03 "vmla.f32 q7, q8, %e14[0] \n" "vmul.f32 q13, q10, %e14[1] \n" "pld [%3, #256] \n" "vmul.f32 q14, q11, %f14[0] \n" "vmul.f32 q15, q12, %f14[1] \n" "vmla.f32 q7, q9, %e15[0] \n" "vld1.f32 {d16-d19}, [%3] \n" "add %3, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %e15[1] \n" "vmla.f32 q13, q10, %f15[0] \n" "pld [%4, #256] \n" "vmla.f32 q14, q11, %f15[1] \n" "vmla.f32 q15, q12, %e16[0] \n" "vmla.f32 q7, q9, %e16[1] \n" "vld1.f32 {d16-d19}, [%4] \n" "add %4, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %f16[0] \n" "vmla.f32 q13, q10, %f16[1] \n" "pld [%5, #256] \n" "vmla.f32 q14, q11, %e17[0] \n" "vmla.f32 q15, q12, %e17[1] \n" "vmla.f32 q7, q9, %f17[0] \n" "vld1.f32 {d16-d19}, [%5] \n" "add %5, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %f17[1] \n" "vmla.f32 q13, q10, %e18[0] \n" "pld [%6, #256] \n" "vmla.f32 q14, q11, %e18[1] \n" "vmla.f32 q15, q12, %f18[0] \n" "vmla.f32 q7, q9, %f18[1] \n" "vld1.f32 {d16-d19}, [%6] \n" "add %6, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vext.32 q12, q8, q9, #3 \n" "vmla.f32 q7, q8, %e19[0] \n" "vmla.f32 q13, q10, %e19[1] \n" "vmla.f32 q14, q11, %f19[0] \n" "vmla.f32 q15, q12, %f19[1] \n" "vmla.f32 q7, q9, %e20[0] \n" "vadd.f32 q14, q14, q15 \n" "vadd.f32 q7, q7, q13 \n" // "veor q15, q15 \n"// _sum3 = 0; "pld [%2, #256] \n" "vadd.f32 q7, q7, q14 \n" "vld1.f32 {d16-d19}, [%2] \n"// _r00 = vld1q_f32(r0+j); "add %2, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "pld [%1, #128] \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); float32x4_t _sum = vmulq_f32(_r0, _k0123); float32x4_t _r1 = vld1q_f32(r1); _sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1)); float32x4_t _r2 = vld1q_f32(r2); _sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2)); float32x4_t _r3 = vld1q_f32(r3); _sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3)); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); float32x4_t _k_t4; _k_t4 = vsetq_lane_f32(k0[4], _k_t4, 0); _k_t4 = vsetq_lane_f32(k1[4], _k_t4, 1); _k_t4 = vsetq_lane_f32(k2[4], _k_t4, 2); _k_t4 = vsetq_lane_f32(k3[4], _k_t4, 3); float32x4_t _r_t4; _r_t4 = vsetq_lane_f32(r0[4], _r_t4, 0); _r_t4 = vsetq_lane_f32(r1[4], _r_t4, 1); _r_t4 = vsetq_lane_f32(r2[4], _r_t4, 2); _r_t4 = vsetq_lane_f32(r3[4], _r_t4, 3); _sum = vmlaq_f32(_sum, _r_t4, _k_t4); sum = r4[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); sum += vget_lane_f32(_ss, 0); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; #endif *outptr += sum; r0++; r1++; r2++; r3++; r4++; outptr++; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; } } } } static void conv5x5s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); for (int q=0; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch*25 + q*25; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; const float* r4 = img0 + w*4; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k4567 = vld1q_f32(kernel0+4); float32x4_t _k891011 = vld1q_f32(kernel0+8); float32x4_t _k12131415 = vld1q_f32(kernel0+12); float32x4_t _k16171819 = vld1q_f32(kernel0+16); float32x4_t _k20212223 = vld1q_f32(kernel0+20); float32x4_t _k24242424 = vdupq_n_f32(kernel0[24]); #endif // __ARM_NEON for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw - (nn << 2); #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n"// v8 = 0 2 4 6 q9 = 1 3 5 7 "prfm pldl1keep, [%2, #256] \n" "ld2 {v10.4s, v11.4s}, [%2] \n"// v10 = 8 10 12 14 v11 = 9 11 13 15 "prfm pldl1keep, [%1, #128] \n" "0: \n" "ld1 {v7.4s}, [%1] \n" // v7 = outptr "ext v12.16b, v8.16b, v10.16b, #4 \n" // v12 = 2 4 6 8 "ext v11.16b, v9.16b, v11.16b, #4 \n" // v11 = 3 5 7 9 "ext v10.16b, v8.16b, v10.16b, #8 \n" // v10 = 4 6 8 10 "fmla v7.4s, v8.4s, %14.s[0] \n" "fmul v13.4s, v9.4s, %14.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "fmul v14.4s, v12.4s, %14.s[2] \n" "fmul v15.4s, v11.4s, %14.s[3] \n" "fmla v7.4s, v10.4s, %15.s[0] \n" "ld2 {v8.4s, v9.4s}, [%3], #32 \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v10.4s, v11.4s}, [%3] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %15.s[1] \n" "fmla v13.4s, v9.4s, %15.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "fmla v14.4s, v12.4s, %15.s[3] \n" "fmla v15.4s, v11.4s, %16.s[0] \n" "fmla v7.4s, v10.4s, %16.s[1] \n" "ld2 {v8.4s, v9.4s}, [%4], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v10.4s, v11.4s}, [%4] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %16.s[2] \n" "fmla v13.4s, v9.4s, %16.s[3] \n" "prfm pldl1keep, [%5, #256] \n" "fmla v14.4s, v12.4s, %17.s[0] \n" "fmla v15.4s, v11.4s, %17.s[1] \n" "fmla v7.4s, v10.4s, %17.s[2] \n" "ld2 {v8.4s, v9.4s}, [%5], #32 \n" "prfm pldl1keep, [%5, #256] \n" "ld2 {v10.4s, v11.4s}, [%5] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %17.s[3] \n" "fmla v13.4s, v9.4s, %18.s[0] \n" "prfm pldl1keep, [%6, #256] \n" "fmla v14.4s, v12.4s, %18.s[1] \n" "fmla v15.4s, v11.4s, %18.s[2] \n" "fmla v7.4s, v10.4s, %18.s[3] \n" "ld2 {v8.4s, v9.4s}, [%6], #32 \n" "prfm pldl1keep, [%6, #256] \n" "ld2 {v10.4s, v11.4s}, [%6] \n" "ext v12.16b, v8.16b, v10.16b, #4 \n" "ext v11.16b, v9.16b, v11.16b, #4 \n" "ext v10.16b, v8.16b, v10.16b, #8 \n" "fmla v7.4s, v8.4s, %19.s[0] \n" "fmla v13.4s, v9.4s, %19.s[1] \n" "fmla v14.4s, v12.4s, %19.s[2] \n" "fmla v15.4s, v11.4s, %19.s[3] \n" "fmla v7.4s, v10.4s, %20.s[0] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2], #32 \n" "fadd v14.4s, v14.4s, v15.4s \n" "fadd v7.4s, v7.4s, v13.4s \n" "prfm pldl1keep, [%2, #256] \n" "fadd v7.4s, v7.4s, v14.4s \n" "ld2 {v10.4s, v11.4s}, [%2] \n" "st1 {v7.4s}, [%1], #16 \n" "prfm pldl1keep, [%1, #128] \n" "subs %w0, %w0, #1 \n" "bne 0b \n" "sub %2, %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #else if (nn > 0) { asm volatile( // "veor q15, q15 \n"// _sump3 = 0; // "veor q13, q13 \n"// _sump2 = 0; // "veor q14, q14 \n"// _sump3 = 0; "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2]! \n"// q8 = 0 2 4 6 q9 = 1 3 5 7 "pld [%2, #256] \n" "vld2.f32 {d20-d23}, [%2] \n"// q10 = 8 10 12 14 q11 = 9 11 13 15 "pld [%1, #128] \n" "0: \n" "vld1.f32 {d14-d15}, [%1] \n"// q7 = outptr "vext.32 q12, q8, q10, #1 \n"// q12 = 2 4 6 8 "vext.32 q11, q9, q11, #1 \n"// q11 = 3 5 7 9 "vext.32 q10, q8, q10, #2 \n"// q10 = 4 6 8 10 "vmla.f32 q7, q8, %e14[0] \n" "vmul.f32 q13, q9, %e14[1] \n" "pld [%3, #256] \n" "vmul.f32 q14, q12, %f14[0] \n" "vmul.f32 q15, q11, %f14[1] \n" "vmla.f32 q7, q10, %e15[0] \n" "vld2.f32 {d16-d19}, [%3]! \n" "pld [%3, #256] \n" "vld2.f32 {d20-d23}, [%3] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %e15[1] \n" "vmla.f32 q13, q9, %f15[0] \n" "pld [%4, #256] \n" "vmla.f32 q14, q12, %f15[1] \n" "vmla.f32 q15, q11, %e16[0] \n" "vmla.f32 q7, q10, %e16[1] \n" "vld2.f32 {d16-d19}, [%4]! \n" "pld [%4, #256] \n" "vld2.f32 {d20-d23}, [%4] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %f16[0] \n" "vmla.f32 q13, q9, %f16[1] \n" "pld [%5, #256] \n" "vmla.f32 q14, q12, %e17[0] \n" "vmla.f32 q15, q11, %e17[1] \n" "vmla.f32 q7, q10, %f17[0] \n" "vld2.f32 {d16-d19}, [%5]! \n" "pld [%5, #256] \n" "vld2.f32 {d20-d23}, [%5] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %f17[1] \n" "vmla.f32 q13, q9, %e18[0] \n" "pld [%6, #256] \n" "vmla.f32 q14, q12, %e18[1] \n" "vmla.f32 q15, q11, %f18[0] \n" "vmla.f32 q7, q10, %f18[1] \n" "vld2.f32 {d16-d19}, [%6]! \n" "pld [%6, #256] \n" "vld2.f32 {d20-d23}, [%6] \n" "vext.32 q12, q8, q10, #1 \n" "vext.32 q11, q9, q11, #1 \n" "vext.32 q10, q8, q10, #2 \n" "vmla.f32 q7, q8, %e19[0] \n" "vmla.f32 q13, q9, %e19[1] \n" "vmla.f32 q14, q12, %f19[0] \n" "vmla.f32 q15, q11, %f19[1] \n" "vmla.f32 q7, q10, %e20[0] \n" "pld [%2, #256] \n" "vld2.f32 {d16-d19}, [%2]! \n"// q8 = 0 2 4 6 q9 = 1 3 5 7 "vadd.f32 q14, q14, q15 \n" "vadd.f32 q7, q7, q13 \n" // "veor q15, q15 \n"// _sump3 = 0; // "veor q13, q13 \n"// _sump2 = 0; "pld [%2, #256] \n" "vadd.f32 q7, q7, q14 \n" "vld2.f32 {d20-d23}, [%2] \n"// q10 = 8 10 12 14 q11 = 9 11 13 15 // "veor q14, q14 \n"// _sump3 = 0; "vst1.f32 {d14-d15}, [%1]! \n" "pld [%1, #128] \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3), // %5 "=r"(r4) // %6 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "6"(r4), "w"(_k0123), // %14 "w"(_k4567), // %15 "w"(_k891011), // %16 "w"(_k12131415), // %17 "w"(_k16171819), // %18 "w"(_k20212223), // %19 "w"(_k24242424) // %20 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = 0; #if __ARM_NEON float32x4_t _r0 = vld1q_f32(r0); float32x4_t _sum = vmulq_f32(_r0, _k0123); float32x4_t _r1 = vld1q_f32(r1); _sum = vmlaq_f32(_sum, _r1, vld1q_f32(k1)); float32x4_t _r2 = vld1q_f32(r2); _sum = vmlaq_f32(_sum, _r2, vld1q_f32(k2)); float32x4_t _r3 = vld1q_f32(r3); _sum = vmlaq_f32(_sum, _r3, vld1q_f32(k3)); float32x4_t _r4 = vld1q_f32(r4); _sum = vmlaq_f32(_sum, _r4, _k20212223); sum += r0[4] * k0[4]; sum += r1[4] * k1[4]; sum += r2[4] * k2[4]; sum += r3[4] * k3[4]; sum += r4[4] * k4[4]; float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); sum += vget_lane_f32(_ss, 0); #else sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; #endif *outptr += sum; r0 += 2; r1 += 2; r2 += 2; r3 += 2; r4 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; r4 += tailstep; } } } }
dfe.c
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @file src/backends/mpi/blrm/dfe.c * @version 1.3.0 * @author Aleksandr Mikhalev * @date 2017-11-07 * */ #include "common.h" #include "starsh.h" #include "starsh-mpi.h" double starsh_blrm__dfe_mpi(STARSH_blrm *matrix) //! Approximation error in Frobenius norm of double precision matrix. /*! Measure error of approximation of a dense matrix by block-wise low-rank * matrix. * * @param[in] matrix: Block-wise low-rank matrix. * @return Error of approximation. * @ingroup blrm * */ { STARSH_blrm *M = matrix; STARSH_blrf *F = M->format; STARSH_problem *P = F->problem; STARSH_kernel *kernel = P->kernel; // Shortcuts to information about clusters STARSH_cluster *R = F->row_cluster; STARSH_cluster *C = F->col_cluster; void *RD = R->data, *CD = C->data; // Number of far-field and near-field blocks STARSH_int nblocks_far_local = F->nblocks_far_local; STARSH_int nblocks_near_local = F->nblocks_near_local; STARSH_int lbi; STARSH_int nblocks_local = nblocks_far_local+nblocks_near_local; // Shortcut to all U and V factors Array **U = M->far_U, **V = M->far_V; // Special constant for symmetric case double sqrt2 = sqrt(2.); // Temporary arrays to compute norms more precisely with dnrm2 double block_norm[nblocks_local], far_block_diff[nblocks_far_local]; double *far_block_norm = block_norm; double *near_block_norm = block_norm+nblocks_far_local; char symm = F->symm; int info; // Simple cycle over all far-field blocks #pragma omp parallel for schedule(dynamic, 1) for(lbi = 0; lbi < nblocks_far_local; lbi++) { STARSH_int bi = F->block_far_local[lbi]; // Get indexes and sizes of block row and column STARSH_int i = F->block_far[2*bi]; STARSH_int j = F->block_far[2*bi+1]; int nrows = R->size[i]; int ncols = C->size[j]; // Rank of a block int rank = M->far_rank[lbi]; // Temporary array for more precise dnrm2 double *D, D_norm[ncols]; size_t D_size = (size_t)nrows*(size_t)ncols; STARSH_PMALLOC(D, D_size, info); // Get actual elements of a block kernel(nrows, ncols, R->pivot+R->start[i], C->pivot+C->start[j], RD, CD, D, nrows); // Get Frobenius norm of a block for(STARSH_int k = 0; k < ncols; k++) D_norm[k] = cblas_dnrm2(nrows, D+k*(size_t)nrows, 1); double tmpnorm = cblas_dnrm2(ncols, D_norm, 1); far_block_norm[lbi] = tmpnorm; // Get difference of initial and approximated block cblas_dgemm(CblasColMajor, CblasNoTrans, CblasTrans, nrows, ncols, rank, -1., U[lbi]->data, nrows, V[lbi]->data, ncols, 1., D, nrows); // Compute Frobenius norm of the latter for(STARSH_int k = 0; k < ncols; k++) D_norm[k] = cblas_dnrm2(nrows, D+k*(size_t)nrows, 1); free(D); double tmpdiff = cblas_dnrm2(ncols, D_norm, 1); far_block_diff[lbi] = tmpdiff; if(i != j && symm == 'S') { // Multiply by square root of 2 in symmetric case // (work on 1 block instead of 2 blocks) far_block_norm[lbi] *= sqrt2; far_block_diff[lbi] *= sqrt2; } } if(M->onfly == 0) // Simple cycle over all near-field blocks #pragma omp parallel for schedule(dynamic, 1) for(lbi = 0; lbi < nblocks_near_local; lbi++) { STARSH_int bi = F->block_near_local[lbi]; // Get indexes and sizes of corresponding block row and column STARSH_int i = F->block_near[2*bi]; STARSH_int j = F->block_near[2*bi+1]; int nrows = R->size[i]; int ncols = C->size[j]; // Compute norm of a block double *D = M->near_D[lbi]->data, D_norm[ncols]; for(STARSH_int k = 0; k < ncols; k++) D_norm[k] = cblas_dnrm2(nrows, D+k*(size_t)nrows, 1); near_block_norm[lbi] = cblas_dnrm2(ncols, D_norm, 1); if(i != j && symm == 'S') // Multiply by square root of 2 in symmetric case near_block_norm[lbi] *= sqrt2; } else // Simple cycle over all near-field blocks #pragma omp parallel for schedule(dynamic, 1) for(lbi = 0; lbi < nblocks_near_local; lbi++) { STARSH_int bi = F->block_near_local[lbi]; // Get indexes and sizes of corresponding block row and column STARSH_int i = F->block_near[2*bi]; STARSH_int j = F->block_near[2*bi+1]; int nrows = R->size[i]; int ncols = C->size[j]; double *D, D_norm[ncols]; // Allocate temporary array and fill it with elements of a block STARSH_PMALLOC(D, (size_t)nrows*(size_t)ncols, info); kernel(nrows, ncols, R->pivot+R->start[i], C->pivot+C->start[j], RD, CD, D, nrows); // Compute norm of a block for(STARSH_int k = 0; k < ncols; k++) D_norm[k] = cblas_dnrm2(nrows, D+k*(size_t)nrows, 1); // Free temporary buffer free(D); near_block_norm[lbi] = cblas_dnrm2(ncols, D_norm, 1); if(i != j && symm == 'S') // Multiply by square root of 2 ub symmetric case near_block_norm[lbi] *= sqrt2; } // Get difference of initial and approximated matrices double value[2]; value[0] = cblas_dnrm2(nblocks_far_local, far_block_diff, 1); // Get norm of initial matrix value[1] = cblas_dnrm2(nblocks_local, block_norm, 1); value[0] *= value[0]; value[1] *= value[1]; double mpi_value[2] = {0, 0}; MPI_Allreduce(&value, &mpi_value, 2, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); return sqrt(mpi_value[0]/mpi_value[1]); }
GB_unop__identity_uint16_uint64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__identity_uint16_uint64 // op(A') function: GB_unop_tran__identity_uint16_uint64 // C type: uint16_t // A type: uint64_t // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint16_t z = (uint16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = (uint16_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_UINT16 || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_uint16_uint64 ( uint16_t *Cx, // Cx and Ax may be aliased const uint64_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint64_t aij = Ax [p] ; uint16_t z = (uint16_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_uint16_uint64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
ten_tusscher_2004_epi_S2_2.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S2_2.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } //TODO: this should be called only once for the whole mesh, like in the GPU code SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5236591284772,0.00130241284471985,0.778613483022969,0.778472769811598,0.000175875277625194,0.484626058693879,0.00294965177778795,0.999998333317616,1.94791112184908e-08,1.90234417053386e-05,0.999779558473224,1.00713872511970,0.999995965310622,4.41551215458988e-05,0.567040008888733,10.2464162625462,139.303734550690}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; ///#ifdef EPI real Gks=0.245; ///#endif ///#ifdef ENDO /// real Gks=0.245; ///#endif ///#ifdef MCELL /// real Gks=0.062; ///#endif //Parameters for Ik1 real GK1=5.405; //Parameters for Ito //#ifdef EPI real Gto=0.294; //#endif // #ifdef ENDO // real Gto=0.073; //#endif //#ifdef MCELL // real Gto=0.294; ///#endif //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={14.2751110459407,0.000197490405913840,0.000138093676576538,0.000459611951400222,0.248312214169369,0.146550920650185,0.141336894566835,4.51002424199619,0.0147942147525980,1.60874334855823,1098.91591518736,0.000497071049372500,0.357179450926053,0.0190817376935230,0.00515881032161095,3.63348608264117e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; ///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; ///Ileak=0.00008f*(CaSR-Cai); Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; #ifdef EPI R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif #ifdef ENDO R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+28)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.; #endif #ifdef MCELL R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
racey_tasks.c
// // This is a very simple program to play with tasks. // // the idea is to print one of two strings // // I think race cars are fun. // I think car races are fun // // This is a race condition since depending on how the // threads are scheduled, you will get a different answer. // We aren't writing any variables. Hence this is not // a data race and the program is legal. // #include <stdio.h> #include <omp.h> int main() { printf("I think"); #pragma omp parallel { #pragma omp single { #pragma omp task printf(" car"); #pragma omp task printf(" race"); } } printf("s"); printf(" are fun!\n"); }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; struct LoopHint; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class OMPClause; class ObjCTypeParamList; struct OMPTraitProperty; struct OMPTraitSelector; struct OMPTraitSet; class OMPTraitInfo; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class ParsingOpenMPDirectiveRAII; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; /// Tracks an expected type for the current token when parsing an expression. /// Used by code completion for ranking. PreferredTypeBuilder PreferredType; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; mutable IdentifierInfo *Ident_abstract; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool, Ident_Bool - cached IdentifierInfos for "vector" /// and "bool" fast comparison. Only present if AltiVec or ZVector are /// enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; IdentifierInfo *Ident_Bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. IdentifierInfo *Ident_instancetype; /// Identifier for "introduced". IdentifierInfo *Ident_introduced; /// Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// Identifier for "message". IdentifierInfo *Ident_message; /// Identifier for "strict". IdentifierInfo *Ident_strict; /// Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++11 contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++2a contextual keywords. mutable IdentifierInfo *Ident_import; mutable IdentifierInfo *Ident_module; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> PCSectionHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> FloatControlHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> MSOptimize; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> UnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> NoUnrollAndJamHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<PragmaHandler> STDCFenvAccessHandler; std::unique_ptr<PragmaHandler> STDCFenvRoundHandler; std::unique_ptr<PragmaHandler> STDCCXLIMITHandler; std::unique_ptr<PragmaHandler> STDCUnknownHandler; std::unique_ptr<PragmaHandler> AttributePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensHerePragmaHandler; std::unique_ptr<PragmaHandler> MaxTokensTotalPragmaHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// Parsing OpenMP directive mode. bool OpenMPDirectiveParsing = false; /// When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// Gets set to true after calling ProduceSignatureHelp, it is for a /// workaround to make sure ProduceSignatureHelp is only called at the deepest /// function call. bool CalledSignatureHelp = false; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// Current kind of OpenMP clause OpenMPClauseKind OMPClauseKind = llvm::omp::OMPC_unknown; /// RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } void setAddedDepth(unsigned D) { Depth = Depth - AddedLevels + D; AddedLevels = D; } unsigned getDepth() const { return Depth; } unsigned getOriginalDepth() const { return Depth - AddedLevels; } }; /// Factory object for creating ParsedAttr objects. AttributeFactory AttrFactory; /// Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; void MaybeDestroyTemplateIds() { if (!TemplateIds.empty() && (Tok.is(tok::eof) || !PP.mightHavePendingAnnotationTokens())) DestroyTemplateIds(); } void DestroyTemplateIds(); /// RAII object to destroy TemplateIdAnnotations where possible, from a /// likely-good position during parsing. struct DestroyTemplateIdAnnotationsRAIIObj { Parser &Self; DestroyTemplateIdAnnotationsRAIIObj(Parser &Self) : Self(Self) {} ~DestroyTemplateIdAnnotationsRAIIObj() { Self.MaybeDestroyTemplateIds(); } }; /// Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; /// Tracker for '<' tokens that might have been intended to be treated as an /// angle bracket instead of a less-than comparison. /// /// This happens when the user intends to form a template-id, but typoes the /// template-name or forgets a 'template' keyword for a dependent template /// name. /// /// We track these locations from the point where we see a '<' with a /// name-like expression on its left until we see a '>' or '>>' that might /// match it. struct AngleBracketTracker { /// Flags used to rank candidate template names when there is more than one /// '<' in a scope. enum Priority : unsigned short { /// A non-dependent name that is a potential typo for a template name. PotentialTypo = 0x0, /// A dependent name that might instantiate to a template-name. DependentName = 0x2, /// A space appears before the '<' token. SpaceBeforeLess = 0x0, /// No space before the '<' token NoSpaceBeforeLess = 0x1, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue*/ DependentName) }; struct Loc { Expr *TemplateName; SourceLocation LessLoc; AngleBracketTracker::Priority Priority; unsigned short ParenCount, BracketCount, BraceCount; bool isActive(Parser &P) const { return P.ParenCount == ParenCount && P.BracketCount == BracketCount && P.BraceCount == BraceCount; } bool isActiveOrNested(Parser &P) const { return isActive(P) || P.ParenCount > ParenCount || P.BracketCount > BracketCount || P.BraceCount > BraceCount; } }; SmallVector<Loc, 8> Locs; /// Add an expression that might have been intended to be a template name. /// In the case of ambiguity, we arbitrarily select the innermost such /// expression, for example in 'foo < bar < baz', 'bar' is the current /// candidate. No attempt is made to track that 'foo' is also a candidate /// for the case where we see a second suspicious '>' token. void add(Parser &P, Expr *TemplateName, SourceLocation LessLoc, Priority Prio) { if (!Locs.empty() && Locs.back().isActive(P)) { if (Locs.back().Priority <= Prio) { Locs.back().TemplateName = TemplateName; Locs.back().LessLoc = LessLoc; Locs.back().Priority = Prio; } } else { Locs.push_back({TemplateName, LessLoc, Prio, P.ParenCount, P.BracketCount, P.BraceCount}); } } /// Mark the current potential missing template location as having been /// handled (this happens if we pass a "corresponding" '>' or '>>' token /// or leave a bracket scope). void clear(Parser &P) { while (!Locs.empty() && Locs.back().isActiveOrNested(P)) Locs.pop_back(); } /// Get the current enclosing expression that might hve been intended to be /// a template name. Loc *getCurrent(Parser &P) { if (!Locs.empty() && Locs.back().isActive(P)) return &Locs.back(); return nullptr; } }; AngleBracketTracker AngleBrackets; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; /// Whether to skip parsing of function bodies. /// /// This option can be used, for example, to speed up searches for /// declarations/definitions when indexing. bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; /// Flags describing a context in which we're parsing a statement. enum class ParsedStmtContext { /// This context permits declarations in language modes where declarations /// are not statements. AllowDeclarationsInC = 0x1, /// This context permits standalone OpenMP directives. AllowStandaloneOpenMPDirectives = 0x2, /// This context is at the top level of a GNU statement expression. InStmtExpr = 0x4, /// The context of a regular substatement. SubStmt = 0, /// The context of a compound-statement. Compound = AllowDeclarationsInC | AllowStandaloneOpenMPDirectives, LLVM_MARK_AS_BITMASK_ENUM(InStmtExpr) }; /// Act on an expression statement that might be the last statement in a /// GNU statement expression. Checks whether we are actually at the end of /// a statement expression and builds a suitable expression statement. StmtResult handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx); public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result, bool IsFirstDecl = false); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion, /// annotation tokens and balanced tokens must be handled using the specific /// consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); if (Tok.isAnnotation()) return ConsumeAnnotationToken(); return ConsumeToken(); } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.isOneOf(tok::l_paren, tok::r_paren); } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.isOneOf(tok::l_square, tok::r_square); } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.isOneOf(tok::l_brace, tok::r_brace); } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion) || Tok.isAnnotation(); } /// Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed, /*IsReinject*/true); PP.Lex(Tok); PP.EnterToken(Next, /*IsReinject*/true); } SourceLocation ConsumeAnnotationToken() { assert(Tok.isAnnotation() && "wrong consume method"); SourceLocation Loc = Tok.getLocation(); PrevTokLocation = Tok.getAnnotationEndLoc(); PP.Lex(Tok); return Loc; } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) { AngleBrackets.clear(*this); --ParenCount; // Don't let unbalanced )'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) { AngleBrackets.clear(*this); --BracketCount; // Don't let unbalanced ]'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) { AngleBrackets.clear(*this); --BraceCount; // Don't let unbalanced }'s drive the count negative. } PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// Checks if the \p Level is valid for use in a fold expression. bool isFoldOperator(prec::Level Level) const; /// Checks if the \p Kind is a valid operator for fold expressions. bool isFoldOperator(tok::TokenKind Kind) const; /// Initialize all pragma handlers. void initializePragmaHandlers(); /// Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// Handle the annotation token produced for /// #pragma STDC FENV_ACCESS... void HandlePragmaFEnvAccess(); /// Handle the annotation token produced for /// #pragma STDC FENV_ROUND... void HandlePragmaFEnvRound(); /// Handle the annotation token produced for /// #pragma float_control void HandlePragmaFloatControl(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); bool ParsePragmaAttributeSubjectMatchRuleSet( attr::ParsedSubjectMatchRuleSet &SubjectMatchRules, SourceLocation &AnyLoc, SourceLocation &LastMatchRuleEndLoc); void HandlePragmaAttribute(); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static TypeResult getTypeAnnotation(const Token &Tok) { if (!Tok.getAnnotationValue()) return TypeError(); return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, TypeResult T) { assert((T.isInvalid() || T.get()) && "produced a valid-but-null type annotation?"); Tok.setAnnotationValue(T.isInvalid() ? nullptr : T.get().getAsOpaquePtr()); } static NamedDecl *getNonTypeAnnotation(const Token &Tok) { return static_cast<NamedDecl*>(Tok.getAnnotationValue()); } static void setNonTypeAnnotation(Token &Tok, NamedDecl *ND) { Tok.setAnnotationValue(ND); } static IdentifierInfo *getIdentifierAnnotation(const Token &Tok) { return static_cast<IdentifierInfo*>(Tok.getAnnotationValue()); } static void setIdentifierAnnotation(Token &Tok, IdentifierInfo *ND) { Tok.setAnnotationValue(ND); } /// Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(const Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); bool MightBeCXXScopeToken() { return Tok.is(tok::identifier) || Tok.is(tok::coloncolon) || (Tok.is(tok::annot_template_id) && NextToken().is(tok::coloncolon)) || Tok.is(tok::kw_decltype) || Tok.is(tok::kw___super); } bool TryAnnotateOptionalCXXScopeToken(bool EnteringContext = false) { return MightBeCXXScopeToken() && TryAnnotateCXXScopeToken(EnteringContext); } private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(CorrectionCandidateCallback *CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && Tok.getIdentifierInfo() != Ident_Bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; PreferredTypeBuilder PrevPreferredType; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser &p) : P(p), PrevPreferredType(P.PreferredType) { PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.PreferredType = PrevPreferredType; P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, DeclSpec::TST T = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); /// Kinds of compound pseudo-tokens formed by a sequence of two real tokens. enum class CompoundToken { /// A '(' '{' beginning a statement-expression. StmtExprBegin, /// A '}' ')' ending a statement-expression. StmtExprEnd, /// A '[' '[' beginning a C++11 or C2x attribute. AttrBegin, /// A ']' ']' ending a C++11 or C2x attribute. AttrEnd, /// A '::' '*' forming a C++ pointer-to-member declaration. MemberPtr, }; /// Check that a compound operator was written in a "sensible" way, and warn /// if not. void checkCompoundToken(SourceLocation FirstTokLoc, tok::TokenKind FirstTokKind, CompoundToken Op); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// Introduces zero or more scopes for parsing. The scopes will all be exited /// when the object is destroyed. class MultiParseScope { Parser &Self; unsigned NumScopes = 0; MultiParseScope(const MultiParseScope&) = delete; public: MultiParseScope(Parser &Self) : Self(Self) {} void Enter(unsigned ScopeFlags) { Self.EnterScope(ScopeFlags); ++NumScopes; } void Exit() { while (NumScopes) { Self.ExitScope(); --NumScopes; } } ~MultiParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); /// Re-enter the template scopes for a declaration that might be a template. unsigned ReenterTemplateScopes(MultiParseScope &S, Decl *D); private: /// RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. Balances (), [], and {} delimiter tokens while /// skipping. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); /// The location of the first statement inside an else that might /// have a missleading indentation. If there is no /// MisleadingIndentationChecker on an else active, this location is invalid. SourceLocation MisleadingIndentationElseLoc; private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); virtual void ParseLexedPragmas(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; void ParseLexedPragmas() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; IdentifierInfo *MacroII = nullptr; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; /// Contains the lexed tokens of a pragma with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. class LateParsedPragma : public LateParsedDeclaration { Parser *Self = nullptr; AccessSpecifier AS = AS_none; CachedTokens Toks; public: explicit LateParsedPragma(Parser *P, AccessSpecifier AS) : Self(P), AS(AS) {} void takeToks(CachedTokens &Cached) { Toks.swap(Cached); } const CachedTokens &toks() const { return Toks; } AccessSpecifier getAccessSpecifier() const { return AS; } void ParseLexedPragmas() override; }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; explicit LexedMethod(Parser *P, Decl *MD) : Self(P), D(MD) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser *Self; /// Method - The method declaration. Decl *Method; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) {} /// Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// Whether this class is an __interface. bool IsInterface : 1; /// The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// The kind of template we are parsing. enum { /// We are not parsing a template at all. NonTemplate = 0, /// We are parsing a template declaration. Template, /// We are parsing an explicit specialization. ExplicitSpecialization, /// We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; // In ParseCXXInlineMethods.cpp. struct ReenterTemplateScopeRAII; struct ReenterClassScopeRAII; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, ParsedAttributes &AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers &VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); void ParseLexedPragmas(ParsingClass &Class); void ParseLexedPragma(LateParsedPragma &LP); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc is filled with the location of the last token of the simple-asm. ExprResult ParseSimpleAsm(bool ForAsmLabel, SourceLocation *EndLoc); ExprResult ParseAsmStringLiteral(bool ForAsmLabel); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(ParsedAttributesWithRange &Attrs); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc, ParsedAttributes &Attrs); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, DeclaratorContext Ctx, ParsedAttributes *ParamAttrs); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpressionInExprEvalContext( TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseCaseExpression(SourceLocation CaseLoc); ExprResult ParseConstraintExpression(); ExprResult ParseConstraintLogicalAndExpression(bool IsTrailingRequiresClause); ExprResult ParseConstraintLogicalOrExpression(bool IsTrailingRequiresClause); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, bool IsUnevaluated); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); /// Control what ParseCastExpression will parse. enum CastParseKind { AnyCastExpr = 0, UnaryExprOnly, PrimaryExprOnly }; ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); ExprResult ParseCastExpression(CastParseKind ParseKind, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false, bool *NotPrimaryExpression = nullptr); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } bool diagnoseUnknownTemplateId(ExprResult TemplateName, SourceLocation Less); void checkPotentialAngleBracket(ExprResult &PotentialTemplateName); bool checkPotentialAngleBracketDelimiter(const AngleBracketTracker::Loc &, const Token &OpToken); bool checkPotentialAngleBracketDelimiter(const Token &OpToken) { if (auto *Info = AngleBrackets.getCurrent(*this)) return checkPotentialAngleBracketDelimiter(*Info, OpToken); return false; } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseSYCLUniqueStableNameExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, llvm::function_ref<void()> ExpressionStarts = llvm::function_ref<void()>()); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' FoldExpr, // Also allow fold-expression <anything> CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHasErrors, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false, bool InUsingDeclaration = false); //===--------------------------------------------------------------------===// // C++11 5.1.2: Lambda expressions /// Result of tentatively parsing a lambda-introducer. enum class LambdaIntroducerTentativeParse { /// This appears to be a lambda-introducer, which has been fully parsed. Success, /// This is a lambda-introducer, but has not been fully parsed, and this /// function needs to be called again to parse it. Incomplete, /// This is definitely an Objective-C message send expression, rather than /// a lambda-introducer, attribute-specifier, or array designator. MessageSend, /// This is not a lambda-introducer. Invalid, }; // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); bool ParseLambdaIntroducer(LambdaIntroducer &Intro, LambdaIntroducerTentativeParse *Tentative = nullptr); ExprResult ParseLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); /// Parse a __builtin_bit_cast(T, E), used to implement C++2a std::bit_cast. ExprResult ParseBuiltinBitCast(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range, bool MayBeFollowedByDirectInit); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while/for condition expression. struct ForRangeInfo; Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK, ForRangeInfo *FRI = nullptr, bool EnterForConditionScope = false); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C++ Concepts ExprResult ParseRequiresExpression(); void ParseTrailingRequiresClause(Declarator &D); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); struct DesignatorCompletionInfo { SmallVectorImpl<Expr *> &InitExprs; QualType PreferredBaseType; }; ExprResult ParseInitializerWithPotentialDesignator(DesignatorCompletionInfo); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, ParsedStmtContext StmtCtx = ParsedStmtContext::SubStmt); StmtResult ParseStatementOrDeclaration( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(ParsedStmtContext StmtCtx); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs, ParsedStmtContext StmtCtx); StmtResult ParseCaseStatement(ParsedStmtContext StmtCtx, bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(ParsedStmtContext StmtCtx); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); bool ConsumeNullStmt(StmtVector &Stmts); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK, SourceLocation *LParenLoc = nullptr, SourceLocation *RParenLoc = nullptr); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, ParsedStmtContext StmtCtx, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// Parse the block; this code is always used. IEB_Parse, /// Skip the block entirely; this code is never used. IEB_Skip, /// Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// The location of the initial keyword. SourceLocation KeywordLoc; /// Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// Nested-name-specifier preceding the name. CXXScopeSpec SS; /// The name we're looking for. UnqualifiedId Name; /// The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, ParsedAttributes &AccessAttrs, AccessSpecifier &CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc, ParsedStmtContext StmtCtx); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum class DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_param, // template parameter context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: return false; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Whether a defining-type-specifier is permitted in a given context. enum class AllowDefiningTypeSpec { /// The grammar doesn't allow a defining-type-specifier here, and we must /// not parse one (eg, because a '{' could mean something else). No, /// The grammar doesn't allow a defining-type-specifier here, but we permit /// one for error recovery purposes. Sema will reject. NoButErrorRecovery, /// The grammar allows a defining-type-specifier here, even though it's /// always invalid. Sema will reject. YesButInvalid, /// The grammar allows a defining-type-specifier here, and one can be valid. Yes }; /// Is this a context in which we are parsing defining-type-specifiers (and /// so permit class and enum definitions in addition to non-defining class and /// enum elaborated-type-specifiers)? static AllowDefiningTypeSpec isDefiningTypeSpecifierContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: return AllowDefiningTypeSpec::Yes; case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: return AllowDefiningTypeSpec::YesButInvalid; case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: return AllowDefiningTypeSpec::NoButErrorRecovery; case DeclSpecContext::DSC_trailing: return AllowDefiningTypeSpec::No; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which an opaque-enum-declaration can appear? static bool isOpaqueEnumDeclarationContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: return true; case DeclSpecContext::DSC_alias_declaration: case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_type_specifier: case DeclSpecContext::DSC_trailing: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DeclSpecContext::DSC_normal: case DeclSpecContext::DSC_template_param: case DeclSpecContext::DSC_class: case DeclSpecContext::DSC_top_level: case DeclSpecContext::DSC_condition: case DeclSpecContext::DSC_type_specifier: return true; case DeclSpecContext::DSC_objc_method_result: case DeclSpecContext::DSC_template_type_arg: case DeclSpecContext::DSC_trailing: case DeclSpecContext::DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; struct ForRangeInfo : ForRangeInit { StmtResult LoopVar; }; DeclGroupPtrTy ParseDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, SourceLocation *DeclSpecStart = nullptr); DeclGroupPtrTy ParseSimpleDeclaration(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr, SourceLocation *DeclSpecStart = nullptr); bool MightBeDeclarator(DeclaratorContext Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, DeclaratorContext Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(DeclaratorContext Context); void ParseDeclarationSpecifiers( DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition( DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList( DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DeclSpecContext::DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, DeclaratorContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, DeclSpec::TST TagType, RecordDecl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().OpenMP) Actions.startOpenMPLoop(); if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. ForRangeDecl, ///< Disambiguated as a for-range declaration. Error ///< Can't be any of the above! }; /// Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt, bool CanBeForRangeDecl); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// Determine whether we could have an enum-base. /// /// \p AllowSemi If \c true, then allow a ';' after the enum-base; otherwise /// only consider this to be an enum-base if the next token is a '{'. /// /// \return \c false if this cannot possibly be an enum base; \c true /// otherwise. bool isEnumBase(bool AllowSemi); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *InvalidAsDeclSpec = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// Determine whether the current token sequence might be /// '<' template-argument-list '>' /// rather than a less-than expression. TPResult isTemplateArgumentList(unsigned TokensToSkip); /// Determine whether an '(' after an 'explicit' keyword is part of a C++20 /// 'explicit(bool)' declaration, in earlier language modes where that is an /// extension. TPResult isExplicitBool(); /// Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier = true, bool mayHaveDirectInit = false); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); /// Try to skip a possibly empty sequence of 'attribute-specifier's without /// full validation of the syntactic structure of attributes. bool TrySkipAttributes(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, DeclaratorContext Context = DeclaratorContext::TypeName, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); /// Are [[]] attributes enabled? bool standardAttributesAllowed() const { const LangOptions &LO = getLangOpts(); return LO.DoubleSquareBracketAttributes; } // Check for the start of an attribute-specifier-seq in a context where an // attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!standardAttributesAllowed() || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!standardAttributesAllowed()) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); // FixItLoc = possible correct location for the attributes void ProhibitAttributes(ParsedAttributesWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clear(); } void ProhibitAttributes(ParsedAttributesViewWithRange &Attrs, SourceLocation FixItLoc = SourceLocation()) { if (Attrs.Range.isInvalid()) return; DiagnoseProhibitedAttributes(Attrs.Range, FixItLoc); Attrs.clearListOnly(); } void DiagnoseProhibitedAttributes(const SourceRange &Range, SourceLocation FixItLoc); // Forbid C++11 and C2x attributes that appear on certain syntactic locations // which standard permits but we don't supported yet, for example, attributes // appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID, bool DiagnoseEmptyAttrs = false); /// 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(); /// Emit warnings for C++11 and C2x attributes that are in a position that /// clang accepts as an extension. void DiagnoseCXX11AttributeExtension(ParsedAttributesWithRange &Attrs); /// 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); enum ParseAttrKindMask { PAKM_GNU = 1 << 0, PAKM_Declspec = 1 << 1, PAKM_CXX11 = 1 << 2, }; /// \brief Parse attributes based on what syntaxes are desired, allowing for /// the order to vary. e.g. with PAKM_GNU | PAKM_Declspec: /// __attribute__((...)) __declspec(...) __attribute__((...))) /// Note that Microsoft attributes (spelled with single square brackets) are /// not supported by this because of parsing ambiguities with other /// constructs. /// /// There are some attribute parse orderings that should not be allowed in /// arbitrary order. e.g., /// /// [[]] __attribute__(()) int i; // OK /// __attribute__(()) [[]] int i; // Not OK /// /// Such situations should use the specific attribute parsing functionality. void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr); void ParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseAttributes(WhichAttrKinds, AttrsWithRange, End, LateAttrs); Attrs.takeAllFrom(AttrsWithRange); } /// \brief Possibly parse attributes based on what syntaxes are desired, /// allowing for the order to vary. bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributesWithRange &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } bool MaybeParseAttributes(unsigned WhichAttrKinds, ParsedAttributes &Attrs, SourceLocation *End = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.isOneOf(tok::kw___attribute, tok::kw___declspec) || (standardAttributesAllowed() && isCXX11AttributeSpecifier())) { ParseAttributes(WhichAttrKinds, Attrs, End, LateAttrs); return true; } return false; } 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); } } /// Parses GNU-style attributes and returns them without source range /// information. /// /// This API is discouraged. Use the version that takes a /// ParsedAttributesWithRange instead. bool MaybeParseGNUAttributes(ParsedAttributes &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseGNUAttributes(Attrs, EndLoc, LateAttrs); Attrs.takeAllFrom(AttrsWithRange); return true; } return false; } bool MaybeParseGNUAttributes(ParsedAttributesWithRange &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParseGNUAttributes(Attrs, EndLoc, LateAttrs); return true; } return false; } /// Parses GNU-style attributes and returns them without source range /// information. /// /// This API is discouraged. Use the version that takes a /// ParsedAttributesWithRange instead. void ParseGNUAttributes(ParsedAttributes &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr) { ParsedAttributesWithRange AttrsWithRange(AttrFactory); ParseGNUAttributes(AttrsWithRange, EndLoc, LateAttrs, D); Attrs.takeAllFrom(AttrsWithRange); } void ParseGNUAttributes(ParsedAttributesWithRange &Attrs, SourceLocation *EndLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } bool MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); return true; } return false; } bool MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (standardAttributesAllowed() && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) { ParseCXX11Attributes(attrs, endLoc); return true; } return false; } 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); bool MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) { ParseMicrosoftDeclSpecs(Attrs, End); return true; } return false; } 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); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseSwiftNewTypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, ParsedAttr::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); ExprResult ParseExtIntegerArgument(); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; bool isClassCompatibleKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); void InitCXXThisScopeForDeclaratorIfRelevant( const Declarator &D, const DeclSpec &DS, llvm::Optional<Sema::CXXThisScopeRAII> &ThisScope); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( DeclaratorContext DeclaratorContext, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(DeclaratorContext Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); struct InnerNamespaceInfo { SourceLocation NamespaceLoc; SourceLocation InlineLoc; SourceLocation IdentLoc; IdentifierInfo *Ident; }; using InnerNamespaceInfoList = llvm::SmallVector<InnerNamespaceInfo, 4>; void ParseInnerNamespace(const InnerNamespaceInfoList &InnerNSs, unsigned int index, SourceLocation &InlineLoc, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, DeclaratorContext Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(DeclaratorContext Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(DeclaratorContext Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributesWithRange &Attrs, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, ParsedAttributes &Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse a property kind into \p TIProperty for the selector set \p Set and /// selector \p Selector. void parseOMPTraitPropertyKind(OMPTraitProperty &TIProperty, llvm::omp::TraitSet Set, llvm::omp::TraitSelector Selector, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector kind into \p TISelector for the selector set \p Set. void parseOMPTraitSelectorKind(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parse a selector set kind into \p TISet. void parseOMPTraitSetKind(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context property. void parseOMPContextProperty(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &Seen); /// Parses an OpenMP context selector. void parseOMPContextSelector(OMPTraitSelector &TISelector, llvm::omp::TraitSet Set, llvm::StringMap<SourceLocation> &SeenSelectors); /// Parses an OpenMP context selector set. void parseOMPContextSelectorSet(OMPTraitSet &TISet, llvm::StringMap<SourceLocation> &SeenSets); /// Parses OpenMP context selectors. bool parseOMPContextSelectors(SourceLocation Loc, OMPTraitInfo &TI); /// Parse a `match` clause for an '#pragma omp declare variant'. Return true /// if there was an error. bool parseOMPDeclareVariantMatchClause(SourceLocation Loc, OMPTraitInfo &TI, OMPTraitInfo *ParentTI); /// Parse clauses for '#pragma omp declare variant'. void ParseOMPDeclareVariantClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// Parse 'omp [begin] assume[s]' directive. void ParseOpenMPAssumesDirective(OpenMPDirectiveKind DKind, SourceLocation Loc); /// Parse 'omp end assumes' directive. void ParseOpenMPEndAssumesDirective(SourceLocation Loc); /// Parse clauses for '#pragma omp [begin] declare target'. void ParseOMPDeclareTargetClauses(Sema::DeclareTargetContextInfo &DTCI); /// Parse '#pragma omp end declare target'. void ParseOMPEndDeclareTargetDirective(OpenMPDirectiveKind BeginDKind, OpenMPDirectiveKind EndDKind, SourceLocation Loc); /// Skip tokens until a `annot_pragma_openmp_end` was found. Emit a warning if /// it is not the current token. void skipUntilPragmaOpenMPEnd(OpenMPDirectiveKind DKind); /// Check the \p FoundKind against the \p ExpectedKind, if not issue an error /// that the "end" matching the "begin" directive of kind \p BeginKind was not /// found. Finally, if the expected kind was found or if \p SkipUntilOpenMPEnd /// is set, skip ahead using the helper `skipUntilPragmaOpenMPEnd`. void parseOMPEndDirective(OpenMPDirectiveKind BeginKind, OpenMPDirectiveKind ExpectedKind, OpenMPDirectiveKind FoundKind, SourceLocation MatchingLoc, SourceLocation FoundLoc, bool SkipUntilOpenMPEnd); /// Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, bool Delayed = false, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// Parses initializer for provided omp_priv declaration inside the reduction /// initializer. void ParseOpenMPReductionInitializerForDecl(VarDecl *OmpPrivParm); /// Parses 'omp declare mapper' directive. DeclGroupPtrTy ParseOpenMPDeclareMapperDirective(AccessSpecifier AS); /// Parses variable declaration in 'omp declare mapper' directive. TypeResult parseOpenMPDeclareMapperVarDecl(SourceRange &Range, DeclarationName &Name, AccessSpecifier AS = AS_none); /// Tries to parse cast part of OpenMP array shaping operation: /// '[' expression ']' { '[' expression ']' } ')'. bool tryParseOpenMPArrayShapingCastPart(); /// Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// Parses declarative or executable directive. /// /// \param StmtCtx The context in which we're parsing the directive. StmtResult ParseOpenMPDeclarativeOrExecutableDirective(ParsedStmtContext StmtCtx); /// Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind, bool ParseOnly); /// Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param DKind Directive kind. /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses the 'sizes' clause of a '#pragma omp tile' directive. OMPClause *ParseOpenMPSizesClause(); /// Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind, bool ParseOnly = false); /// Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, bool ParseOnly); /// Parses and creates OpenMP 5.0 iterators expression: /// <iterators> = 'iterator' '(' { [ <iterator-type> ] identifier = /// <range-specification> }+ ')' ExprResult ParseOpenMPIteratorsExpr(); /// Parses allocators and traits in the context of the uses_allocator clause. /// Expected format: /// '(' { <allocator> [ '(' <allocator_traits> ')' ] }+ ')' OMPClause *ParseOpenMPUsesAllocatorClause(OpenMPDirectiveKind DKind); /// Parses clause with an interop variable of kind \a Kind. /// /// \param Kind Kind of current clause. /// \param ParseOnly true to skip the clause's semantic actions and return /// nullptr. // OMPClause *ParseOpenMPInteropClause(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 *DepModOrTailExpr = nullptr; SourceLocation ColonLoc; SourceLocation RLoc; CXXScopeSpec ReductionOrMapperIdScopeSpec; DeclarationNameInfo ReductionOrMapperId; int ExtraModifier = -1; ///< Additional modifier for linear, map, depend or ///< lastprivate clause. SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> MapTypeModifiers; SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> MapTypeModifiersLoc; SmallVector<OpenMPMotionModifierKind, NumberOfOMPMotionModifiers> MotionModifiers; SmallVector<SourceLocation, NumberOfOMPMotionModifiers> MotionModifiersLoc; bool IsMapTypeImplicit = false; SourceLocation ExtraModifierLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, ParsedType ObjectType, bool ObjectHadErrors, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, SourceLocation *TemplateKWLoc, UnqualifiedId &Result); /// Parses the mapper modifier in map, to, and from clauses. bool parseMapperModifier(OpenMPVarListDataTy &Data); /// Parses map-type-modifiers in map clause. /// map([ [map-type-modifier[,] [map-type-modifier[,] ...] map-type : ] list) /// where, map-type-modifier ::= always | close | mapper(mapper-identifier) bool parseMapTypeModifiers(OpenMPVarListDataTy &Data); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); Decl *ParseTemplateDeclarationOrSpecialization(DeclaratorContext Context, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS); Decl *ParseSingleDeclarationAfterTemplate( DeclaratorContext Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); bool ParseTemplateParameters(MultiParseScope &TemplateScopes, unsigned Depth, SmallVectorImpl<NamedDecl *> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<NamedDecl*> &TemplateParams); TPResult isStartOfTemplateTypeParameter(); NamedDecl *ParseTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTypeParameter(unsigned Depth, unsigned Position); NamedDecl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); NamedDecl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); bool isTypeConstraintAnnotation(); bool TryAnnotateTypeConstraint(); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation LAngleLoc, SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true, bool TypeConstraint = false); void AnnotateTemplateIdTokenAsType(CXXScopeSpec &SS, bool IsClassName = false); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(DeclaratorContext Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, ParsedAttributes &AccessAttrs, AccessSpecifier AS = AS_none); // C++2a: Template, concept definition [temp] Decl * ParseConceptDefinition(const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(bool IsFirstDecl); Decl *ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled) override; void CodeCompleteNaturalLanguage() override; class GNUAsmQualifiers { unsigned Qualifiers = AQ_unspecified; public: enum AQ { AQ_unspecified = 0, AQ_volatile = 1, AQ_inline = 2, AQ_goto = 4, }; static const char *getQualifierName(AQ Qualifier); bool setAsmQualifier(AQ Qualifier); inline bool isVolatile() const { return Qualifiers & AQ_volatile; }; inline bool isInline() const { return Qualifiers & AQ_inline; }; inline bool isGoto() const { return Qualifiers & AQ_goto; } }; bool isGCCAsmStatement(const Token &TokAfterAsm) const; bool isGNUAsmQualifier(const Token &TokAfterAsm) const; GNUAsmQualifiers::AQ getGNUAsmQualifier(const Token &Tok) const; bool parseGNUAsmQualifierListOpt(GNUAsmQualifiers &AQ); }; } // end namespace clang #endif
normsq.c
// Jacobi 3D skeleton program #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "timing.h" int main(int argc, char** argv) { double wct_start,wct_end,cput_start,cput_end,runtime,r; int iter,size,i,j,k,n; double *f1, *f2; iter=1000; double mintime = 4.0; if (argc != 2 && argc != 3) { printf("Usage: %s <size> [mintime]\n",argv[0]); exit(1); } if (argc == 3) { mintime = atof(argv[2]); } size = atoi(argv[1]); f1 = malloc((size_t)size*sizeof(double)); f2 = malloc((size_t)size*sizeof(double)); #pragma omp parallel for schedule(static) for (i = 0; i < size; i++) { f1[i] = sin( (double) i * i); f2[i] = cos( (double) 2*i); } // time measurement timing(&wct_start, &cput_start); double sum = 0.0; while (1) { timing(&wct_start, &cput_start); for (j = 0; j < iter; j++) { #pragma omp parallel for reduction(+:sum) schedule(static) for (i = 0; i < size; i++) { sum += f1[i]*f1[i]; } } timing(&wct_end, &cput_end); // making sure mintime was spent, otherwise restart with 2*iter if (wct_end - wct_start > mintime) { break; } iter = iter * 2; } runtime = wct_end - wct_start; printf("size:\t%d\ttime/iter:\t%lf\tGFLOP/s:\t%lf\n", size, runtime/iter, ((double)iter) * size * 1e-9 / runtime); return 0; }
conversion.h
#ifndef _CONVERSION_H #define _CONVERSION_H #include <comms/glb.h> CPS_START_NAMESPACE #if 1 #define NOINLINE_MACRO __attribute((noinline)) #else #define NOINLINE_MACRO #endif inline void moveFloattofloat (float *out, Float * in, size_t f_size) { Float sum=0.; #pragma omp parallel for reduction(+:sum) for (size_t i = 0; i < f_size; i++) { out[i]=in[i]; // flt = (float) in[i]; // out[i] = flt; sum +=out[i]*out[i]; } glb_sum(&sum); // VRB.Result("","moveFloattofloat()","norm=%e\n",sum); }; inline void movefloattoFloat (Float * out, float *in, size_t f_size) { // float flt; Float sum=0.; #pragma omp parallel for reduction(+:sum) for (size_t i = 0; i < f_size; i++) { out[i]=in[i]; // flt = in[i]; // out[i] = (Float) flt; sum +=out[i]*out[i]; } glb_sum(&sum); // VRB.Result("","moveFloattofloat()","norm=%e\n",sum); }; CPS_END_NAMESPACE #endif
efp.c
/*- * Copyright (c) 2012-2017 Ilya Kaliman * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include <stdio.h> #include <stdlib.h> #include "balance.h" #include "clapack.h" #include "elec.h" #include "private.h" #include "stream.h" static void update_fragment(struct frag *frag) { /* update atoms */ for (size_t i = 0; i < frag->n_atoms; i++) efp_move_pt(CVEC(frag->x), &frag->rotmat, CVEC(frag->lib->atoms[i].x), VEC(frag->atoms[i].x)); efp_update_elec(frag); efp_update_pol(frag); efp_update_disp(frag); efp_update_xr(frag); } static enum efp_result set_coord_xyzabc(struct frag *frag, const double *coord) { frag->x = coord[0]; frag->y = coord[1]; frag->z = coord[2]; euler_to_matrix(coord[3], coord[4], coord[5], &frag->rotmat); update_fragment(frag); return EFP_RESULT_SUCCESS; } static enum efp_result set_coord_points(struct frag *frag, const double *coord) { /* allow fragments with less than 3 atoms by using multipole points of * ghost atoms; multipole points have the same coordinates as atoms */ if (frag->n_multipole_pts < 3) { efp_log("fragment must contain at least three atoms"); return EFP_RESULT_FATAL; } double ref[9] = { frag->lib->multipole_pts[0].x, frag->lib->multipole_pts[0].y, frag->lib->multipole_pts[0].z, frag->lib->multipole_pts[1].x, frag->lib->multipole_pts[1].y, frag->lib->multipole_pts[1].z, frag->lib->multipole_pts[2].x, frag->lib->multipole_pts[2].y, frag->lib->multipole_pts[2].z }; vec_t p1; mat_t rot1, rot2; efp_points_to_matrix(coord, &rot1); efp_points_to_matrix(ref, &rot2); rot2 = mat_transpose(&rot2); frag->rotmat = mat_mat(&rot1, &rot2); p1 = mat_vec(&frag->rotmat, VEC(frag->lib->multipole_pts[0].x)); /* center of mass */ frag->x = coord[0] - p1.x; frag->y = coord[1] - p1.y; frag->z = coord[2] - p1.z; update_fragment(frag); return EFP_RESULT_SUCCESS; } static enum efp_result set_coord_rotmat(struct frag *frag, const double *coord) { if (!efp_check_rotation_matrix((const mat_t *)(coord + 3))) { efp_log("invalid rotation matrix specified"); return EFP_RESULT_FATAL; } frag->x = coord[0]; frag->y = coord[1]; frag->z = coord[2]; memcpy(&frag->rotmat, coord + 3, sizeof(frag->rotmat)); update_fragment(frag); return EFP_RESULT_SUCCESS; } static void free_frag(struct frag *frag) { if (!frag) return; free(frag->atoms); free(frag->multipole_pts); free(frag->polarizable_pts); free(frag->dynamic_polarizable_pts); free(frag->lmo_centroids); free(frag->xr_fock_mat); free(frag->xr_wf); free(frag->xrfit); free(frag->screen_params); free(frag->ai_screen_params); for (size_t i = 0; i < 3; i++) free(frag->xr_wf_deriv[i]); for (size_t i = 0; i < frag->n_xr_atoms; i++) { for (size_t j = 0; j < frag->xr_atoms[i].n_shells; j++) free(frag->xr_atoms[i].shells[j].coef); free(frag->xr_atoms[i].shells); } free(frag->xr_atoms); /* don't do free(frag) here */ } static enum efp_result copy_frag(struct frag *dest, const struct frag *src) { size_t size; memcpy(dest, src, sizeof(*dest)); if (src->atoms) { size = src->n_atoms * sizeof(struct efp_atom); dest->atoms = (struct efp_atom *)malloc(size); if (!dest->atoms) return EFP_RESULT_NO_MEMORY; memcpy(dest->atoms, src->atoms, size); } if (src->multipole_pts) { size = src->n_multipole_pts * sizeof(struct multipole_pt); dest->multipole_pts = (struct multipole_pt *)malloc(size); if (!dest->multipole_pts) return EFP_RESULT_NO_MEMORY; memcpy(dest->multipole_pts, src->multipole_pts, size); } if (src->screen_params) { size = src->n_multipole_pts * sizeof(double); dest->screen_params = (double *)malloc(size); if (!dest->screen_params) return EFP_RESULT_NO_MEMORY; memcpy(dest->screen_params, src->screen_params, size); } if (src->ai_screen_params) { size = src->n_multipole_pts * sizeof(double); dest->ai_screen_params = (double *)malloc(size); if (!dest->ai_screen_params) return EFP_RESULT_NO_MEMORY; memcpy(dest->ai_screen_params, src->ai_screen_params, size); } if (src->polarizable_pts) { size = src->n_polarizable_pts * sizeof(struct polarizable_pt); dest->polarizable_pts = (struct polarizable_pt *)malloc(size); if (!dest->polarizable_pts) return EFP_RESULT_NO_MEMORY; memcpy(dest->polarizable_pts, src->polarizable_pts, size); } if (src->dynamic_polarizable_pts) { size = src->n_dynamic_polarizable_pts * sizeof(struct dynamic_polarizable_pt); dest->dynamic_polarizable_pts = (struct dynamic_polarizable_pt *)malloc(size); if (!dest->dynamic_polarizable_pts) return EFP_RESULT_NO_MEMORY; memcpy(dest->dynamic_polarizable_pts, src->dynamic_polarizable_pts, size); } if (src->lmo_centroids) { size = src->n_lmo * sizeof(vec_t); dest->lmo_centroids = (vec_t *)malloc(size); if (!dest->lmo_centroids) return EFP_RESULT_NO_MEMORY; memcpy(dest->lmo_centroids, src->lmo_centroids, size); } if (src->xr_atoms) { size = src->n_xr_atoms * sizeof(struct xr_atom); dest->xr_atoms = (struct xr_atom *)malloc(size); if (!dest->xr_atoms) return EFP_RESULT_NO_MEMORY; memcpy(dest->xr_atoms, src->xr_atoms, size); for (size_t j = 0; j < src->n_xr_atoms; j++) { const struct xr_atom *at_src = src->xr_atoms + j; struct xr_atom *at_dest = dest->xr_atoms + j; size = at_src->n_shells * sizeof(struct shell); at_dest->shells = (struct shell *)malloc(size); if (!at_dest->shells) return EFP_RESULT_NO_MEMORY; memcpy(at_dest->shells, at_src->shells, size); for (size_t i = 0; i < at_src->n_shells; i++) { size = (at_src->shells[i].type == 'L' ? 3 : 2) * at_src->shells[i].n_funcs * sizeof(double); at_dest->shells[i].coef = (double *)malloc(size); if (!at_dest->shells[i].coef) return EFP_RESULT_NO_MEMORY; memcpy(at_dest->shells[i].coef, at_src->shells[i].coef, size); } } } if (src->xr_fock_mat) { size = src->n_lmo * (src->n_lmo + 1) / 2 * sizeof(double); dest->xr_fock_mat = (double *)malloc(size); if (!dest->xr_fock_mat) return EFP_RESULT_NO_MEMORY; memcpy(dest->xr_fock_mat, src->xr_fock_mat, size); } if (src->xr_wf) { size = src->n_lmo * src->xr_wf_size * sizeof(double); dest->xr_wf = (double *)malloc(size); if (!dest->xr_wf) return EFP_RESULT_NO_MEMORY; memcpy(dest->xr_wf, src->xr_wf, size); } if (src->xrfit) { size = src->n_lmo * 4 * sizeof(double); dest->xrfit = (double *)malloc(size); if (!dest->xrfit) return EFP_RESULT_NO_MEMORY; memcpy(dest->xrfit, src->xrfit, size); } return EFP_RESULT_SUCCESS; } static enum efp_result check_opts(const struct efp_opts *opts) { if (opts->enable_pbc) { if ((opts->terms & EFP_TERM_AI_ELEC) || (opts->terms & EFP_TERM_AI_POL) || (opts->terms & EFP_TERM_AI_DISP) || (opts->terms & EFP_TERM_AI_XR) || (opts->terms & EFP_TERM_AI_CHTR)) { efp_log("periodic calculations are not supported " "for QM/EFP"); return EFP_RESULT_FATAL; } if (!opts->enable_cutoff) { efp_log("periodic calculations require interaction " "cutoff to be enabled"); return EFP_RESULT_FATAL; } } if (opts->enable_cutoff) { if (opts->swf_cutoff < 1.0) { efp_log("interaction cutoff is too small"); return EFP_RESULT_FATAL; } } return EFP_RESULT_SUCCESS; } static enum efp_result check_frag_params(const struct efp_opts *opts, const struct frag *frag) { if ((opts->terms & EFP_TERM_ELEC) || (opts->terms & EFP_TERM_AI_ELEC)) { if (!frag->multipole_pts) { efp_log("electrostatic parameters are missing"); return EFP_RESULT_FATAL; } if (opts->elec_damp == EFP_ELEC_DAMP_SCREEN && frag->screen_params == NULL) { efp_log("screening parameters are missing"); return EFP_RESULT_FATAL; } } if ((opts->terms & EFP_TERM_POL) || (opts->terms & EFP_TERM_AI_POL)) { if (!frag->polarizable_pts || !frag->multipole_pts) { efp_log("polarization parameters are missing"); return EFP_RESULT_FATAL; } } if ((opts->terms & EFP_TERM_DISP) || (opts->terms & EFP_TERM_AI_DISP)) { if (frag->dynamic_polarizable_pts == NULL) { efp_log("dispersion parameters are missing"); return EFP_RESULT_FATAL; } if (opts->disp_damp == EFP_DISP_DAMP_OVERLAP && frag->n_lmo != frag->n_dynamic_polarizable_pts) { efp_log("number of polarization points does not " "match number of LMOs"); return EFP_RESULT_FATAL; } } if ((opts->terms & EFP_TERM_XR) || (opts->terms & EFP_TERM_AI_XR)) { if (!frag->xr_atoms || !frag->xr_fock_mat || !frag->xr_wf || !frag->lmo_centroids) { efp_log("exchange repulsion parameters are missing"); return EFP_RESULT_FATAL; } } return EFP_RESULT_SUCCESS; } static enum efp_result check_params(struct efp *efp) { enum efp_result res; for (size_t i = 0; i < efp->n_frag; i++) if ((res = check_frag_params(&efp->opts, efp->frags + i))) return res; return EFP_RESULT_SUCCESS; } static int do_elec(const struct efp_opts *opts) { return opts->terms & EFP_TERM_ELEC; } static int do_disp(const struct efp_opts *opts) { return opts->terms & EFP_TERM_DISP; } static int do_xr(const struct efp_opts *opts) { int xr = (opts->terms & EFP_TERM_XR); int cp = (opts->terms & EFP_TERM_ELEC) && (opts->elec_damp == EFP_ELEC_DAMP_OVERLAP); int dd = (opts->terms & EFP_TERM_DISP) && (opts->disp_damp == EFP_DISP_DAMP_OVERLAP); return xr || cp || dd; } static void compute_two_body_range(struct efp *efp, size_t frag_from, size_t frag_to, void *data) { double e_elec = 0.0, e_disp = 0.0, e_xr = 0.0, e_cp = 0.0; (void)data; #ifdef _OPENMP #pragma omp parallel for schedule(dynamic) reduction(+:e_elec,e_disp,e_xr,e_cp) #endif for (size_t i = frag_from; i < frag_to; i++) { size_t cnt = efp->n_frag % 2 ? (efp->n_frag - 1) / 2 : i < efp->n_frag / 2 ? efp->n_frag / 2 : efp->n_frag / 2 - 1; for (size_t j = i + 1; j < i + 1 + cnt; j++) { size_t fr_j = j % efp->n_frag; if (!efp_skip_frag_pair(efp, i, fr_j)) { double *s; six_t *ds; size_t n_lmo_ij = efp->frags[i].n_lmo * efp->frags[fr_j].n_lmo; s = (double *)calloc(n_lmo_ij, sizeof(double)); ds = (six_t *)calloc(n_lmo_ij, sizeof(six_t)); if (do_xr(&efp->opts)) { double exr, ecp; efp_frag_frag_xr(efp, i, fr_j, s, ds, &exr, &ecp); e_xr += exr; e_cp += ecp; } if (do_elec(&efp->opts)) { e_elec += efp_frag_frag_elec(efp, i, fr_j); } if (do_disp(&efp->opts)) { e_disp += efp_frag_frag_disp(efp, i, fr_j, s, ds); } free(s); free(ds); } } } efp->energy.electrostatic += e_elec; efp->energy.dispersion += e_disp; efp->energy.exchange_repulsion += e_xr; efp->energy.charge_penetration += e_cp; } EFP_EXPORT enum efp_result efp_get_energy(struct efp *efp, struct efp_energy *energy) { assert(efp); assert(energy); *energy = efp->energy; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_gradient(struct efp *efp, double *grad) { assert(efp); assert(grad); if (!efp->do_gradient) { efp_log("gradient calculation was not requested"); return EFP_RESULT_FATAL; } memcpy(grad, efp->grad, efp->n_frag * sizeof(six_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_atomic_gradient(struct efp *efp, double *grad) { six_t *efpgrad = NULL; /* Calculated EFP gradient */ vec_t *pgrad; /* Conversion of grad to vec_t type */ size_t i, j, k, l; size_t nr; /* Number of atoms in the current fragment */ size_t maxa; /* Maximum number of size of m, Ia, r arrays */ vec_t *r = NULL; /* Radius-vector of each atom inside current fragment with respect to CoM of that fragment */ double mm, *m = NULL; /* Total Mass of fragments and individual atoms */ double I, *Ia = NULL; /* Inertia along axis and contribution of each individual atom */ mat_t Id; /* Total inertia tensor of a fragment */ vec_t v, g; /* Principal axis and Inertia along that axis */ vec_t rbuf, rbuf2, tq, ri, rt; double dist, sina, ft, norm; enum efp_result res; assert(efp); assert(grad); if (!efp->do_gradient) { efp_log("gradient calculation was not requested"); return EFP_RESULT_FATAL; } pgrad = (vec_t *)grad; /* Calculate maximum size of a fragment */ maxa = 0; for (j = 0; j < efp->n_frag; j++) { if (efp->frags[j].n_atoms > maxa) maxa = efp->frags[j].n_atoms; } res = EFP_RESULT_NO_MEMORY; /* Create and initialize some arrays for work */ if ((r = (vec_t *)malloc(maxa * sizeof(*r))) == NULL) goto error; if ((m = (double *)malloc(maxa * sizeof(*m))) == NULL) goto error; if ((Ia = (double *)malloc(maxa * sizeof(*Ia))) == NULL) goto error; /* Copy computed efp->grad */ if ((efpgrad = (six_t *)malloc(efp->n_frag * sizeof(*efpgrad))) == NULL) goto error; memcpy(efpgrad, efp->grad, efp->n_frag * sizeof(*efpgrad)); /* Main cycle (iterate fragments, distribute forces and torques) */ for (k = 0, j = 0; j < efp->n_frag; j++) { nr = efp->frags[j].n_atoms; memset(r, 0, maxa * sizeof(*r)); memset(m, 0, maxa * sizeof(*m)); memset(Ia, 0, maxa * sizeof(*Ia)); mm = 0.0; Id = mat_zero; v = vec_zero; g = vec_zero; for (i = 0; i < nr ; i++) { r[i].x = efp->frags[j].atoms[i].x - efp->frags[j].x; r[i].y = efp->frags[j].atoms[i].y - efp->frags[j].y; r[i].z = efp->frags[j].atoms[i].z - efp->frags[j].z; m[i] = efp->frags[j].atoms[i].mass; mm += m[i]; /* Inertia tensor contribution calculations */ Id.xx += m[i] * (r[i].y*r[i].y + r[i].z*r[i].z); Id.yy += m[i] * (r[i].x*r[i].x + r[i].z*r[i].z); Id.zz += m[i] * (r[i].x*r[i].x + r[i].y*r[i].y); Id.xy -= m[i] * r[i].x * r[i].y; Id.yx -= m[i] * r[i].x * r[i].y; Id.xz -= m[i] * r[i].x * r[i].z; Id.zx -= m[i] * r[i].x * r[i].z; Id.yz -= m[i] * r[i].y * r[i].z; Id.zy -= m[i] * r[i].y * r[i].z; } /* Try to diagonalize Id and get principal axis */ if (efp_dsyev('V', 'U', 3, (double *)&Id, 3, (double *)&g)) { efp_log("inertia tensor diagonalization failed"); res = EFP_RESULT_FATAL; goto error; } /* Add any additional forces from grad array to efpgrad array */ for (i = 0; i < nr; i++) { efpgrad[j].x += pgrad[k+i].x; efpgrad[j].y += pgrad[k+i].y; efpgrad[j].z += pgrad[k+i].z; rbuf = vec_cross(&r[i], &pgrad[k+i]); efpgrad[j].a += rbuf.x; efpgrad[j].b += rbuf.y; efpgrad[j].c += rbuf.z; pgrad[k+i] = vec_zero; } /* Now we are ready to redistribute efpgrad over the atoms */ /* Redistribute total translation grad[i]=m[i]/mm*efpgrad[j] */ for (i = 0; i < nr; i++) { pgrad[k+i].x = efpgrad[j].x; pgrad[k+i].y = efpgrad[j].y; pgrad[k+i].z = efpgrad[j].z; vec_scale(&pgrad[k+i], m[i] / mm); } /* Redistribution of torque should be done over 3 principal axes computed previously */ for (l = 0; l < 3; l++) { v = ((vec_t *)&Id)[l]; tq.x = efpgrad[j].a; tq.y = efpgrad[j].b; tq.z = efpgrad[j].c; /* Calculate contribution of each atom to moment of inertia with respect to current axis */ I = 0.0; for (i = 0; i < nr; i++) { rbuf = vec_cross(&v, &r[i]); dist = vec_len(&rbuf); Ia[i] = m[i] * dist * dist; I += Ia[i]; } /* Project torque onto v axis */ norm = vec_dot(&tq, &v); tq = v; vec_scale(&tq, norm); /* Now distribute torque using Ia[i]/I as a scale */ for (i = 0; i < nr; i++) { if (eq(Ia[i], 0.0)) continue; /* If atom is not on the current axis */ rbuf = tq; vec_scale(&rbuf, Ia[i]/I); ft = vec_len(&rbuf); ri = r[i]; vec_normalize(&ri); rt = tq; vec_normalize(&rt); rbuf2 = vec_cross(&rt, &ri); sina = vec_len(&rbuf2); vec_normalize(&rbuf2); vec_scale(&rbuf2, ft/sina/vec_len(&r[i])); /* Update grad with torque contribution of atom i over axis v */ pgrad[k+i] = vec_add(&pgrad[k+i], &rbuf2); } } k += nr; } res = EFP_RESULT_SUCCESS; error: free(r); free(m); free(Ia); free(efpgrad); return res; } EFP_EXPORT enum efp_result efp_set_point_charges(struct efp *efp, size_t n_ptc, const double *ptc, const double *xyz) { assert(efp); efp->n_ptc = n_ptc; if (n_ptc == 0) { free(efp->ptc); free(efp->ptc_xyz); free(efp->ptc_grad); efp->ptc = NULL; efp->ptc_xyz = NULL; efp->ptc_grad = NULL; return EFP_RESULT_SUCCESS; } assert(ptc); assert(xyz); efp->ptc = (double *)realloc(efp->ptc, n_ptc * sizeof(double)); efp->ptc_xyz = (vec_t *)realloc(efp->ptc_xyz, n_ptc * sizeof(vec_t)); efp->ptc_grad = (vec_t *)realloc(efp->ptc_grad, n_ptc * sizeof(vec_t)); memcpy(efp->ptc, ptc, n_ptc * sizeof(double)); memcpy(efp->ptc_xyz, xyz, n_ptc * sizeof(vec_t)); memset(efp->ptc_grad, 0, n_ptc * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_point_charge_count(struct efp *efp, size_t *n_ptc) { assert(efp); assert(n_ptc); *n_ptc = efp->n_ptc; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_point_charge_gradient(struct efp *efp, double *grad) { assert(efp); assert(grad); if (!efp->do_gradient) { efp_log("gradient calculation was not requested"); return EFP_RESULT_FATAL; } memcpy(grad, efp->ptc_grad, efp->n_ptc * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_point_charge_coordinates(struct efp *efp, double *xyz) { assert(efp); assert(xyz); memcpy(xyz, efp->ptc_xyz, efp->n_ptc * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_point_charge_coordinates(struct efp *efp, const double *xyz) { assert(efp); assert(xyz); memcpy(efp->ptc_xyz, xyz, efp->n_ptc * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_point_charge_values(struct efp *efp, double *ptc) { assert(efp); assert(ptc); memcpy(ptc, efp->ptc, efp->n_ptc * sizeof(double)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_point_charge_values(struct efp *efp, const double *ptc) { assert(efp); assert(ptc); memcpy(efp->ptc, ptc, efp->n_ptc * sizeof(double)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_coordinates(struct efp *efp, enum efp_coord_type coord_type, const double *coord) { assert(efp); assert(coord); size_t stride; enum efp_result res; switch (coord_type) { case EFP_COORD_TYPE_XYZABC: stride = 6; break; case EFP_COORD_TYPE_POINTS: stride = 9; break; case EFP_COORD_TYPE_ROTMAT: stride = 12; break; } for (size_t i = 0; i < efp->n_frag; i++, coord += stride) if ((res = efp_set_frag_coordinates(efp, i, coord_type, coord))) return res; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_frag_coordinates(struct efp *efp, size_t frag_idx, enum efp_coord_type coord_type, const double *coord) { struct frag *frag; assert(efp); assert(coord); assert(frag_idx < efp->n_frag); frag = efp->frags + frag_idx; switch (coord_type) { case EFP_COORD_TYPE_XYZABC: return set_coord_xyzabc(frag, coord); case EFP_COORD_TYPE_POINTS: return set_coord_points(frag, coord); case EFP_COORD_TYPE_ROTMAT: return set_coord_rotmat(frag, coord); } assert(0); } EFP_EXPORT enum efp_result efp_get_coordinates(struct efp *efp, double *xyzabc) { assert(efp); assert(xyzabc); for (size_t i = 0; i < efp->n_frag; i++) { struct frag *frag = efp->frags + i; double a, b, c; matrix_to_euler(&frag->rotmat, &a, &b, &c); *xyzabc++ = frag->x; *xyzabc++ = frag->y; *xyzabc++ = frag->z; *xyzabc++ = a; *xyzabc++ = b; *xyzabc++ = c; } return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_xyzabc(struct efp *efp, size_t frag_idx, double *xyzabc) { struct frag *frag; double a, b, c; assert(efp); assert(frag_idx < efp->n_frag); assert(xyzabc); frag = efp->frags + frag_idx; matrix_to_euler(&frag->rotmat, &a, &b, &c); xyzabc[0] = frag->x; xyzabc[1] = frag->y; xyzabc[2] = frag->z; xyzabc[3] = a; xyzabc[4] = b; xyzabc[5] = c; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_periodic_box(struct efp *efp, double x, double y, double z) { assert(efp); if (x < 2.0 * efp->opts.swf_cutoff || y < 2.0 * efp->opts.swf_cutoff || z < 2.0 * efp->opts.swf_cutoff) { efp_log("periodic box dimensions must be at least twice " "the switching function cutoff"); return EFP_RESULT_FATAL; } efp->box.x = x; efp->box.y = y; efp->box.z = z; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_periodic_box(struct efp *efp, double *xyz) { assert(efp); assert(xyz); xyz[0] = efp->box.x; xyz[1] = efp->box.y; xyz[2] = efp->box.z; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_stress_tensor(struct efp *efp, double *stress) { assert(efp); assert(stress); if (!efp->do_gradient) { efp_log("gradient calculation was not requested"); return EFP_RESULT_FATAL; } *(mat_t *)stress = efp->stress; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_ai_screen(struct efp *efp, size_t frag_idx, double *screen) { const struct frag *frag; size_t size; assert(efp); assert(screen); assert(frag_idx < efp->n_frag); frag = &efp->frags[frag_idx]; if (frag->ai_screen_params == NULL) { efp_log("no screening parameters found for %s", frag->name); return EFP_RESULT_FATAL; } size = frag->n_multipole_pts * sizeof(double); memcpy(screen, frag->ai_screen_params, size); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_prepare(struct efp *efp) { assert(efp); efp->n_polarizable_pts = 0; for (size_t i = 0; i < efp->n_frag; i++) { efp->frags[i].polarizable_offset = efp->n_polarizable_pts; efp->n_polarizable_pts += efp->frags[i].n_polarizable_pts; } efp->indip = (vec_t *)calloc(efp->n_polarizable_pts, sizeof(vec_t)); efp->indipconj = (vec_t *)calloc(efp->n_polarizable_pts, sizeof(vec_t)); efp->grad = (six_t *)calloc(efp->n_frag, sizeof(six_t)); efp->skiplist = (char *)calloc(efp->n_frag * efp->n_frag, 1); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_orbital_energies(struct efp *efp, size_t n_core, size_t n_act, size_t n_vir, const double *oe) { size_t size; assert(efp); assert(oe); efp->n_ai_core = n_core; efp->n_ai_act = n_act; efp->n_ai_vir = n_vir; size = (n_core + n_act + n_vir) * sizeof(double); efp->ai_orbital_energies = (double *)realloc(efp->ai_orbital_energies, size); memcpy(efp->ai_orbital_energies, oe, size); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_dipole_integrals(struct efp *efp, size_t n_core, size_t n_act, size_t n_vir, const double *dipint) { size_t size; assert(efp); assert(dipint); efp->n_ai_core = n_core; efp->n_ai_act = n_act; efp->n_ai_vir = n_vir; size = 3 * (n_core + n_act + n_vir) * (n_core + n_act + n_vir); efp->ai_dipole_integrals = (double *)realloc(efp->ai_dipole_integrals, size * sizeof(double)); memcpy(efp->ai_dipole_integrals, dipint, size * sizeof(double)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_wavefunction_dependent_energy(struct efp *efp, double *energy) { assert(efp); assert(energy); if (!(efp->opts.terms & EFP_TERM_POL) && !(efp->opts.terms & EFP_TERM_AI_POL)) { *energy = 0.0; return EFP_RESULT_SUCCESS; } return efp_compute_pol_energy(efp, energy); } EFP_EXPORT enum efp_result efp_compute(struct efp *efp, int do_gradient) { enum efp_result res; assert(efp); if (efp->grad == NULL) { efp_log("call efp_prepare after all fragments are added"); return EFP_RESULT_FATAL; } efp->do_gradient = do_gradient; if ((res = check_params(efp))) return res; memset(&efp->energy, 0, sizeof(efp->energy)); memset(&efp->stress, 0, sizeof(efp->stress)); memset(efp->grad, 0, efp->n_frag * sizeof(six_t)); memset(efp->ptc_grad, 0, efp->n_ptc * sizeof(vec_t)); efp_balance_work(efp, compute_two_body_range, NULL); if ((res = efp_compute_pol(efp))) return res; if ((res = efp_compute_ai_elec(efp))) return res; if ((res = efp_compute_ai_disp(efp))) return res; #ifdef EFP_USE_MPI efp_allreduce(&efp->energy.electrostatic, 1); efp_allreduce(&efp->energy.dispersion, 1); efp_allreduce(&efp->energy.exchange_repulsion, 1); efp_allreduce(&efp->energy.charge_penetration, 1); if (efp->do_gradient) { efp_allreduce((double *)efp->grad, 6 * efp->n_frag); efp_allreduce((double *)efp->ptc_grad, 3 * efp->n_ptc); efp_allreduce((double *)&efp->stress, 9); } #endif efp->energy.total = efp->energy.electrostatic + efp->energy.charge_penetration + efp->energy.electrostatic_point_charges + efp->energy.polarization + efp->energy.dispersion + efp->energy.ai_dispersion + efp->energy.exchange_repulsion; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_charge(struct efp *efp, size_t frag_idx, double *charge) { struct frag *frag; double sum = 0.0; size_t i; assert(efp); assert(charge); assert(frag_idx < efp->n_frag); frag = efp->frags + frag_idx; for (i = 0; i < frag->n_atoms; i++) sum += frag->atoms[i].znuc; for (i = 0; i < frag->n_multipole_pts; i++) sum += frag->multipole_pts[i].monopole; *charge = sum; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_multiplicity(struct efp *efp, size_t frag_idx, int *mult) { assert(efp); assert(mult); assert(frag_idx < efp->n_frag); *mult = efp->frags[frag_idx].multiplicity; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_multipole_count(struct efp *efp, size_t frag_idx, size_t *n_mult) { assert(efp); assert(n_mult); assert(frag_idx < efp->n_frag); *n_mult = efp->frags[frag_idx].n_multipole_pts; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_multipole_count(struct efp *efp, size_t *n_mult) { size_t sum = 0; assert(efp); assert(n_mult); for (size_t i = 0; i < efp->n_frag; i++) sum += efp->frags[i].n_multipole_pts; *n_mult = sum; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_multipole_coordinates(struct efp *efp, double *xyz) { assert(efp); assert(xyz); for (size_t i = 0; i < efp->n_frag; i++) { struct frag *frag = efp->frags + i; for (size_t j = 0; j < frag->n_multipole_pts; j++) { *xyz++ = frag->multipole_pts[j].x; *xyz++ = frag->multipole_pts[j].y; *xyz++ = frag->multipole_pts[j].z; } } return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_multipole_values(struct efp *efp, double *mult) { assert(efp); assert(mult); for (size_t i = 0; i < efp->n_frag; i++) { struct frag *frag = efp->frags + i; for (size_t j = 0; j < frag->n_multipole_pts; j++) { struct multipole_pt *pt = frag->multipole_pts + j; *mult++ = pt->monopole; *mult++ = pt->dipole.x; *mult++ = pt->dipole.y; *mult++ = pt->dipole.z; for (size_t t = 0; t < 6; t++) *mult++ = pt->quadrupole[t]; for (size_t t = 0; t < 10; t++) *mult++ = pt->octupole[t]; } } return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_induced_dipole_count(struct efp *efp, size_t *n_dip) { size_t sum = 0; assert(efp); assert(n_dip); for (size_t i = 0; i < efp->n_frag; i++) sum += efp->frags[i].n_polarizable_pts; *n_dip = sum; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_induced_dipole_coordinates(struct efp *efp, double *xyz) { assert(efp); assert(xyz); for (size_t i = 0; i < efp->n_frag; i++) { struct frag *frag = efp->frags + i; for (size_t j = 0; j < frag->n_polarizable_pts; j++) { struct polarizable_pt *pt = frag->polarizable_pts + j; *xyz++ = pt->x; *xyz++ = pt->y; *xyz++ = pt->z; } } return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_induced_dipole_values(struct efp *efp, double *dip) { assert(efp); assert(dip); memcpy(dip, efp->indip, efp->n_polarizable_pts * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_induced_dipole_conj_values(struct efp *efp, double *dip) { assert(efp); assert(dip); memcpy(dip, efp->indipconj, efp->n_polarizable_pts * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_lmo_count(struct efp *efp, size_t frag_idx, size_t *n_lmo) { assert(efp != NULL); assert(frag_idx < efp->n_frag); assert(n_lmo != NULL); *n_lmo = efp->frags[frag_idx].n_lmo; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_lmo_coordinates(struct efp *efp, size_t frag_idx, double *xyz) { struct frag *frag; assert(efp != NULL); assert(frag_idx < efp->n_frag); assert(xyz != NULL); frag = efp->frags + frag_idx; if (frag->lmo_centroids == NULL) { efp_log("no LMO centroids for fragment %s", frag->name); return EFP_RESULT_FATAL; } memcpy(xyz, frag->lmo_centroids, frag->n_lmo * sizeof(vec_t)); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_xrfit(struct efp *efp, size_t frag_idx, double *xrfit) { struct frag *frag; assert(efp != NULL); assert(frag_idx < efp->n_frag); assert(xrfit != NULL); frag = efp->frags + frag_idx; if (frag->xrfit == NULL) { efp_log("no XRFIT parameters for fragment %s", frag->name); return EFP_RESULT_FATAL; } memcpy(xrfit, frag->xrfit, frag->n_lmo * 4 * sizeof(double)); return EFP_RESULT_SUCCESS; } EFP_EXPORT void efp_shutdown(struct efp *efp) { if (efp == NULL) return; for (size_t i = 0; i < efp->n_frag; i++) free_frag(efp->frags + i); for (size_t i = 0; i < efp->n_lib; i++) { free_frag(efp->lib[i]); free(efp->lib[i]); } free(efp->frags); free(efp->lib); free(efp->grad); free(efp->ptc); free(efp->ptc_xyz); free(efp->ptc_grad); free(efp->indip); free(efp->indipconj); free(efp->ai_orbital_energies); free(efp->ai_dipole_integrals); free(efp->skiplist); free(efp); } EFP_EXPORT enum efp_result efp_set_opts(struct efp *efp, const struct efp_opts *opts) { enum efp_result res; assert(efp); assert(opts); if ((res = check_opts(opts))) return res; efp->opts = *opts; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_opts(struct efp *efp, struct efp_opts *opts) { assert(efp); assert(opts); *opts = efp->opts; return EFP_RESULT_SUCCESS; } EFP_EXPORT void efp_opts_default(struct efp_opts *opts) { assert(opts); memset(opts, 0, sizeof(*opts)); opts->terms = EFP_TERM_ELEC | EFP_TERM_POL | EFP_TERM_DISP | EFP_TERM_XR | EFP_TERM_AI_ELEC | EFP_TERM_AI_POL; } EFP_EXPORT void efp_set_error_log(void (*cb)(const char *)) { efp_set_log_cb(cb); } EFP_EXPORT enum efp_result efp_add_fragment(struct efp *efp, const char *name) { const struct frag *lib; assert(efp); assert(name); if (efp->skiplist) { efp_log("cannot add fragments after efp_prepare"); return EFP_RESULT_FATAL; } if ((lib = efp_find_lib(efp, name)) == NULL) { efp_log("cannot find \"%s\" in any of .efp files", name); return EFP_RESULT_UNKNOWN_FRAGMENT; } efp->n_frag++; efp->frags = (struct frag *)realloc(efp->frags, efp->n_frag * sizeof(struct frag)); if (efp->frags == NULL) return EFP_RESULT_NO_MEMORY; enum efp_result res; struct frag *frag = efp->frags + efp->n_frag - 1; if ((res = copy_frag(frag, lib))) return res; for (size_t a = 0; a < 3; a++) { size_t size = frag->xr_wf_size * frag->n_lmo; frag->xr_wf_deriv[a] = (double *)calloc(size, sizeof(double)); if (frag->xr_wf_deriv[a] == NULL) return EFP_RESULT_NO_MEMORY; } return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_skip_fragments(struct efp *efp, size_t i, size_t j, int value) { assert(efp); assert(efp->skiplist); /* call efp_prepare first */ assert(i < efp->n_frag); assert(j < efp->n_frag); efp->skiplist[i * efp->n_frag + j] = value ? 1 : 0; efp->skiplist[j * efp->n_frag + i] = value ? 1 : 0; return EFP_RESULT_SUCCESS; } EFP_EXPORT struct efp * efp_create(void) { struct efp *efp = (struct efp *)calloc(1, sizeof(struct efp)); if (efp == NULL) return NULL; efp_opts_default(&efp->opts); return efp; } EFP_EXPORT enum efp_result efp_set_electron_density_field_fn(struct efp *efp, efp_electron_density_field_fn fn) { assert(efp); efp->get_electron_density_field = fn; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_set_electron_density_field_user_data(struct efp *efp, void *user_data) { assert(efp); efp->get_electron_density_field_user_data = user_data; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_count(struct efp *efp, size_t *n_frag) { assert(efp); assert(n_frag); *n_frag = efp->n_frag; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_name(struct efp *efp, size_t frag_idx, size_t size, char *frag_name) { assert(efp); assert(frag_name); assert(frag_idx < efp->n_frag); strncpy(frag_name, efp->frags[frag_idx].name, size); return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_mass(struct efp *efp, size_t frag_idx, double *mass_out) { assert(efp); assert(mass_out); assert(frag_idx < efp->n_frag); const struct frag *frag = efp->frags + frag_idx; double mass = 0.0; for (size_t i = 0; i < frag->n_atoms; i++) mass += frag->atoms[i].mass; *mass_out = mass; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_inertia(struct efp *efp, size_t frag_idx, double *inertia_out) { assert(efp); assert(inertia_out); assert(frag_idx < efp->n_frag); /* center of mass is in origin and axes are principal axes of inertia */ const struct frag *frag = efp->frags[frag_idx].lib; vec_t inertia = vec_zero; for (size_t i = 0; i < frag->n_atoms; i++) { const struct efp_atom *atom = frag->atoms + i; inertia.x += atom->mass * (atom->y*atom->y + atom->z*atom->z); inertia.y += atom->mass * (atom->x*atom->x + atom->z*atom->z); inertia.z += atom->mass * (atom->x*atom->x + atom->y*atom->y); } inertia_out[0] = inertia.x; inertia_out[1] = inertia.y; inertia_out[2] = inertia.z; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_atom_count(struct efp *efp, size_t frag_idx, size_t *n_atoms) { assert(efp); assert(n_atoms); assert(frag_idx < efp->n_frag); *n_atoms = efp->frags[frag_idx].n_atoms; return EFP_RESULT_SUCCESS; } EFP_EXPORT enum efp_result efp_get_frag_atoms(struct efp *efp, size_t frag_idx, size_t size, struct efp_atom *atoms) { struct frag *frag; assert(efp); assert(atoms); assert(frag_idx < efp->n_frag); assert(size >= efp->frags[frag_idx].n_atoms); frag = efp->frags + frag_idx; memcpy(atoms, frag->atoms, frag->n_atoms * sizeof(struct efp_atom)); return EFP_RESULT_SUCCESS; } EFP_EXPORT void efp_torque_to_derivative(const double *euler, const double *torque, double *deriv) { assert(euler); assert(torque); assert(deriv); double tx = torque[0]; double ty = torque[1]; double tz = torque[2]; double sina = sin(euler[0]); double cosa = cos(euler[0]); double sinb = sin(euler[1]); double cosb = cos(euler[1]); deriv[0] = tz; deriv[1] = cosa * tx + sina * ty; deriv[2] = sinb * sina * tx - sinb * cosa * ty + cosb * tz; } EFP_EXPORT const char * efp_banner(void) { static const char banner[] = "LIBEFP ver. " LIBEFP_VERSION_STRING "\n" "Copyright (c) 2012-2017 Ilya Kaliman\n" "\n" "Journal References:\n" " - Kaliman and Slipchenko, JCC 2013.\n" " DOI: http://dx.doi.org/10.1002/jcc.23375\n" " - Kaliman and Slipchenko, JCC 2015.\n" " DOI: http://dx.doi.org/10.1002/jcc.23772\n" "\n" "Project web site: https://libefp.github.io/\n"; return banner; } EFP_EXPORT void efp_print_banner(void) { puts(efp_banner()); } EFP_EXPORT const char * efp_result_to_string(enum efp_result res) { switch (res) { case EFP_RESULT_SUCCESS: return "Operation was successful."; case EFP_RESULT_FATAL: return "Fatal error has occurred."; case EFP_RESULT_NO_MEMORY: return "Insufficient memory."; case EFP_RESULT_FILE_NOT_FOUND: return "File not found."; case EFP_RESULT_SYNTAX_ERROR: return "Syntax error."; case EFP_RESULT_UNKNOWN_FRAGMENT: return "Unknown EFP fragment."; case EFP_RESULT_POL_NOT_CONVERGED: return "Polarization SCF procedure did not converge."; } assert(0); }
weno5js_impl_c_.c
#include <stdlib.h> #include <math.h> static double eps; static int size; static double c00 = 1.0/3.0; static double c01 = -7.0/6.0; static double c02 = 11.0/6.0; static double c10 = -1.0/6.0; static double c11 = 5.0/6.0; static double c12 = 1.0/3.0; static double c20 = 1.0/3.0; static double c21 = 5.0/6.0; static double c22 = -1.0/6.0; static double isc = 13.0 / 12.0; void weno5js_init(double aeps, int asize) { eps = aeps; size = asize; } void weno5js_interpolate(double *a, double *b, double *c, double *d, double *e, double * restrict out) { double q0, q1, q2; double is0, is1, is2; double alpha0, alpha1, alpha2; double sum_alpha; int i; // Constant is used for auto-vectorization in GCC const int ub = size; #pragma omp simd \ private(q0, q1, q2, is0, is1, is2, alpha0, alpha1, alpha2, sum_alpha) for (i = 0; i < ub; ++i) { q0 = c00*a[i] + c01*b[i] + c02*c[i]; q1 = c10*b[i] + c11*c[i] + c12*d[i]; q2 = c20*c[i] + c21*d[i] + c22*e[i]; is0 = isc * pow(a[i] - 2*b[i] + c[i], 2) + 0.25*pow(a[i] - 4*b[i] + 3*c[i], 2); is1 = isc * pow(b[i] - 2*c[i] + d[i], 2) + 0.25*pow(d[i] - b[i], 2); is2 = isc * pow(c[i] - 2*d[i] + e[i], 2) + 0.25*pow(3*c[i] - 4*d[i] + e[i], 2); alpha0 = 1.0 / ((eps + is0)*(eps + is0)); alpha1 = 6.0 / ((eps + is1)*(eps + is1)); alpha2 = 3.0 / ((eps + is2)*(eps + is2)); sum_alpha = alpha0 + alpha1 + alpha2; out[i] = (alpha0 * q0 + alpha1 * q1 + alpha2 * q2) / sum_alpha; } }
shingles.c
/* * Simple Stencil example * Main program example * * Brian J Gravelle * gravelle@cs.uoregon.edu * */ #ifdef USE_CALI #include <caliper/cali.h> #endif #ifdef USE_LIKWID #include <likwid-marker.h> #endif #include <stdlib.h> #include <stdio.h> #include <string.h> #include <omp.h> //KERNEL #define TRUE 1 #define FALSE 0 void kernel(double *__restrict__ data, size_t nsize, size_t ntrials, size_t *flops, size_t *bytes_per_elem, size_t *mem_accesses_per_elem); struct Inputs { size_t num_thr; size_t nsize; size_t nreps; char print_info; }; void get_input(int argc, char **argv, struct Inputs* input); // main function int main(int argc, char **argv) { #ifdef USE_LIKWID LIKWID_MARKER_INIT; #endif int err = FALSE; double wall_tot_start, wall_tot_end; double wall_init_start, wall_init_end; double wall_comp_start, wall_comp_end; double wall_free_start, wall_free_end; struct Inputs input; size_t ntrials = 1; size_t flops = 0; size_t tot_flops = 0; size_t bytes_per_elem = 0; size_t mem_accesses_per_elem = 0; double** data; double ai = 0.0; double gflops = 0.0; get_input(argc, argv, &input); omp_set_num_threads(input.num_thr); #ifdef USE_CALI cali_id_t thread_attr = cali_create_attribute("thread_id", CALI_TYPE_INT, CALI_ATTR_ASVALUE | CALI_ATTR_SKIP_EVENTS); #pragma omp parallel { cali_set_int(thread_attr, omp_get_thread_num()); } #endif wall_tot_start = wall_init_start = omp_get_wtime(); data = (double **)aligned_alloc(64, input.num_thr*sizeof(double*)); for(size_t tid = 0; tid < input.num_thr; tid++) { data[tid] = (double *)aligned_alloc(64, input.nsize*sizeof(double)); for(size_t j = 0; j < input.nsize; j++) { data[tid][j] = 0.0001; } } if (input.print_info) printf("Running benchmark.......\n"); fflush(stdout); wall_comp_start = wall_init_end = omp_get_wtime(); #pragma omp parallel { #ifdef USE_CALI CALI_MARK_BEGIN("kernel"); #endif size_t tid = omp_get_thread_num(); kernel(data[tid], input.nsize, input.nreps, &flops, &bytes_per_elem, &mem_accesses_per_elem); #ifdef USE_CALI CALI_MARK_END("kernel"); #endif } wall_free_start = wall_comp_end = omp_get_wtime(); free(data); wall_tot_end = wall_free_end = omp_get_wtime(); ai = ((double)flops)/((double)bytes_per_elem*(double)mem_accesses_per_elem); gflops = ((double)flops*(double)input.num_thr*(double)input.nsize*(double)input.nreps)/(wall_comp_end - wall_comp_start); tot_flops = flops*input.nsize;//*input.nreps; if (input.print_info) { printf("\nRan new Shingle with \n\ doubles per thr = %d \n\ flops per iter = %d \n\ flops per thr = %d \n\ Arith Intensity = %f \n\ rep count = %d \n\ thread count = %d \n", input.nsize, flops, tot_flops, ai, input.nreps, input.num_thr); printf("init time: %fs\n", (wall_init_end - wall_init_start)); printf("free time: %fs\n", (wall_free_end - wall_free_start)); printf("\ncomputation time: %fs\n", (wall_comp_end - wall_comp_start)); printf("computation rate: %e FLOP/s\n", gflops); } else { printf("%e\n", gflops); } #ifdef USE_LIKWID LIKWID_MARKER_CLOSE; #endif return err; } void get_input(int argc, char **argv, struct Inputs* input) { int i = 1; input->num_thr = 4; input->nsize = 308224; // 2465792 bytes (308224 doubles) per core on L2 and 3 skylake input->nreps = 5; input->print_info = TRUE; for(i = 1; i < argc; i++) { if ( !(strcmp("-h", argv[i])) || !(strcmp("--help", argv[i])) ) { printf("shingles options:\n"); printf("--threads [] -t [] .......... for number of threads\n"); printf("--size [] -s [] ............. for number of doubles to use per thread\n"); printf("--repititions [] -r [] ...... for number of repititions to perform\n"); printf("--quiet -q .................. to remove output other than computation time\n"); exit(1); } if ( !(strcmp("-t", argv[i])) || !(strcmp("--threads", argv[i])) ) { if (++i < argc){ input->num_thr = atoi(argv[i]); } else { printf("Please include a thread count with that option\n"); exit(1); } } if ( !(strcmp("-s", argv[i])) || !(strcmp("--size", argv[i])) ) { if (++i < argc){ input->nsize = atoi(argv[i]); } else { printf("Please include a number of doubles with that option\n"); exit(1); } } if ( !(strcmp("-r", argv[i])) || !(strcmp("--repititions", argv[i])) ) { if (++i < argc){ input->nreps = atoi(argv[i]); } else { printf("Please include a number of reps with that option\n"); exit(1); } } if ( !(strcmp("-q", argv[i])) || !(strcmp("--quiet", argv[i])) ) { input->print_info = FALSE; } } }
vednnLinearBackwardData.c
#include <stdint.h> #include "vednnLinearBackwardData.h" #ifdef VEDNN_USE_OPENMP #include <omp.h> extern int __vednn_omp_num_threads ; #endif static inline vednnError_t vednnLinearBackwardData_wrapper( vednnLinearBackwardData_t pFunc, const uint64_t inDim, const uint64_t outDim, const uint64_t nBatch, const void *pDataGradOut, const void *pDataWeight, void *pDataGradIn ) { if(nBatch == 1) { return pFunc(inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn); } else { vednnError_t rc = VEDNN_SUCCESS ; #pragma omp parallel reduction(|:rc) { uint64_t nthreads = omp_get_num_threads() ; uint64_t threadid = omp_get_thread_num() ; uint64_t nBatchEach = nBatch / nthreads ; uint64_t remain = nBatch % nthreads ; uint64_t batchBegin = nBatchEach * threadid + ( threadid < remain ? threadid : remain ) ; uint64_t myBatch = nBatchEach + ( threadid < remain ? 1 : 0 ) ; if( myBatch == 0 ) { rc |= VEDNN_SUCCESS ; } else { float* _pDataGradOut = ((float *)pDataGradOut) + batchBegin * outDim ; float* _pDataGradIn = ((float *)pDataGradIn) + batchBegin * inDim ; rc |= pFunc(inDim, outDim, myBatch, _pDataGradOut, pDataWeight, _pDataGradIn); } } return rc; } } /* ----------------------------------------------------------------------- */ vednnError_t vednnLinearBackwardData( const uint64_t inDim, const uint64_t outDim, const uint64_t nBatch, const void *pDataGradOut, const void *pDataWeight, void *pDataGradIn ) { // [todo] add variations if( outDim<=128 && inDim >=256 ) { if( ((outDim&0x1))==0 && ((((uint64_t)pDataWeight)&0x7)==0) ) { return vednnLinearBackwardData_wrapper( vednnLinearBackwardData_o2XU128_waligned, inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn ) ; } else { return vednnLinearBackwardData_wrapper( vednnLinearBackwardData_oU128, inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn ) ; } } else if( outDim <= 256 ) { return vednnLinearBackwardData_wrapper( vednnLinearBackwardData_oU256, inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn ) ; } else if( ((outDim & 0x1) == 0) && ((((uint64_t)pDataWeight)&0x7)==0) && ((((uint64_t)pDataGradOut)&0x7)==0) ) { return vednnLinearBackwardData_wrapper( vednnLinearBackwardData_o2X_woaligned, inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn ) ; } else { return vednnLinearBackwardData_wrapper( vednnLinearBackwardData_default, inDim, outDim, nBatch, pDataGradOut, pDataWeight, pDataGradIn ) ; } }
HybridRepSetReader.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2019 QMCPACK developers. // // File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory ////////////////////////////////////////////////////////////////////////////////////// /** @file * * derived from SplineSetReader */ #ifndef QMCPLUSPLUS_HYBRIDREP_READER_H #define QMCPLUSPLUS_HYBRIDREP_READER_H #include <Numerics/Quadrature.h> #include <Numerics/Bessel.h> #include <QMCWaveFunctions/BsplineFactory/HybridRepCenterOrbitals.h> #include "OhmmsData/AttributeSet.h" #include <config/stdlib/math.hpp> //#include <QMCHamiltonians/Ylm.h> //#define PRINT_RADIAL namespace qmcplusplus { template<typename ST, typename LT> struct Gvectors { typedef TinyVector<ST, 3> PosType; typedef std::complex<ST> ValueType; const LT& Lattice; std::vector<PosType> gvecs_cart; //Cartesian. std::vector<ST> gmag; const size_t NumGvecs; Gvectors(const std::vector<TinyVector<int, 3>>& gvecs_in, const LT& Lattice_in, const TinyVector<int, 3>& HalfG, size_t first, size_t last) : Lattice(Lattice_in), NumGvecs(last - first) { gvecs_cart.resize(NumGvecs); gmag.resize(NumGvecs); #pragma omp parallel for for (size_t ig = 0; ig < NumGvecs; ig++) { TinyVector<ST, 3> gvec_shift; gvec_shift = gvecs_in[ig + first] + HalfG * 0.5; gvecs_cart[ig] = Lattice.k_cart(gvec_shift); gmag[ig] = std::sqrt(dot(gvecs_cart[ig], gvecs_cart[ig])); } } template<typename YLM_ENGINE, typename VVT> void calc_Ylm_G(const size_t ig, YLM_ENGINE& Ylm, VVT& YlmG) const { PosType Ghat(0.0, 0.0, 1.0); if (gmag[ig] > 0) Ghat = gvecs_cart[ig] / gmag[ig]; Ylm.evaluateV(Ghat[0], Ghat[1], Ghat[2], YlmG.data()); } template<typename VVT> inline void calc_jlm_G(const int lmax, ST& r, const size_t ig, VVT& j_lm_G) const { bessel_steed_array_cpu(lmax, gmag[ig] * r, j_lm_G.data()); for (size_t l = lmax; l > 0; l--) for (size_t lm = l * l; lm < (l + 1) * (l + 1); lm++) j_lm_G[lm] = j_lm_G[l]; } template<typename PT, typename VT> inline void calc_phase_shift(const PT& RSoA, const size_t ig, VT& phase_shift_real, VT& phase_shift_imag) const { const ST* restrict px = RSoA.data(0); const ST* restrict py = RSoA.data(1); const ST* restrict pz = RSoA.data(2); ST* restrict v_r = phase_shift_real.data(); ST* restrict v_i = phase_shift_imag.data(); const ST& gv_x = gvecs_cart[ig][0]; const ST& gv_y = gvecs_cart[ig][1]; const ST& gv_z = gvecs_cart[ig][2]; #pragma omp simd aligned(px, py, pz, v_r, v_i) for (size_t iat = 0; iat < RSoA.size(); iat++) qmcplusplus::sincos(px[iat] * gv_x + py[iat] * gv_y + pz[iat] * gv_z, v_i + iat, v_r + iat); } template<typename PT> ValueType evaluate_psi_r(const Vector<std::complex<double>>& cG, const PT& pos) { assert(cG.size() == NumGvecs); std::complex<ST> val(0.0, 0.0); for (size_t ig = 0; ig < NumGvecs; ig++) { ST s, c; qmcplusplus::sincos(dot(gvecs_cart[ig], pos), &s, &c); ValueType pw0(c, s); val += cG[ig] * pw0; } return val; } template<typename PT> void evaluate_psi_r(const Vector<std::complex<double>>& cG, const PT& pos, ValueType& phi, ValueType& d2phi) { assert(cG.size() == NumGvecs); d2phi = phi = 0.0; for (size_t ig = 0; ig < NumGvecs; ig++) { ST s, c; qmcplusplus::sincos(dot(gvecs_cart[ig], pos), &s, &c); ValueType pw0(c, s); phi += cG[ig] * pw0; d2phi += cG[ig] * pw0 * (-dot(gvecs_cart[ig], gvecs_cart[ig])); } } double evaluate_KE(const Vector<std::complex<double>>& cG) { assert(cG.size() == NumGvecs); double KE = 0; for (size_t ig = 0; ig < NumGvecs; ig++) KE += dot(gvecs_cart[ig], gvecs_cart[ig]) * (cG[ig].real() * cG[ig].real() + cG[ig].imag() * cG[ig].imag()); return KE / 2.0; } }; /** General HybridRepSetReader to handle any unitcell */ template<typename SA> struct HybridRepSetReader : public SplineSetReader<SA> { typedef SplineSetReader<SA> BaseReader; using BaseReader::bspline; using BaseReader::mybuilder; using BaseReader::rotate_phase_i; using BaseReader::rotate_phase_r; using typename BaseReader::DataType; HybridRepSetReader(EinsplineSetBuilder* e) : BaseReader(e) {} /** initialize basic parameters of atomic orbitals */ void initialize_hybridrep_atomic_centers() override { OhmmsAttributeSet a; std::string scheme_name("Consistent"); std::string s_function_name("LEKS2018"); a.add(scheme_name, "smoothing_scheme"); a.add(s_function_name, "smoothing_function"); a.put(mybuilder->XMLRoot); // assign smooth_scheme if (scheme_name == "Consistent") bspline->smooth_scheme = SA::smoothing_schemes::CONSISTENT; else if (scheme_name == "SmoothAll") bspline->smooth_scheme = SA::smoothing_schemes::SMOOTHALL; else if (scheme_name == "SmoothPartial") bspline->smooth_scheme = SA::smoothing_schemes::SMOOTHPARTIAL; else APP_ABORT("initialize_hybridrep_atomic_centers wrong smoothing_scheme name! Only allows Consistent, SmoothAll or " "SmoothPartial."); // assign smooth_function if (s_function_name == "LEKS2018") bspline->smooth_func_id = smoothing_functions::LEKS2018; else if (s_function_name == "coscos") bspline->smooth_func_id = smoothing_functions::COSCOS; else if (s_function_name == "linear") bspline->smooth_func_id = smoothing_functions::LINEAR; else APP_ABORT( "initialize_hybridrep_atomic_centers wrong smoothing_function name! Only allows LEKS2018, coscos or linear."); app_log() << "Hybrid orbital representation uses " << scheme_name << " smoothing scheme and " << s_function_name << " smoothing function." << std::endl; bspline->set_info(*(mybuilder->SourcePtcl), mybuilder->TargetPtcl, mybuilder->Super2Prim); auto& centers = bspline->AtomicCenters; auto& ACInfo = mybuilder->AtomicCentersInfo; // load atomic center info only when it is not initialized if (centers.size() == 0) { bool success = true; app_log() << "Reading atomic center info for hybrid representation" << std::endl; for (int center_idx = 0; center_idx < ACInfo.Ncenters; center_idx++) { const int my_GroupID = ACInfo.GroupID[center_idx]; if (ACInfo.cutoff[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'cutoff_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.inner_cutoff[center_idx] < 0) { const double inner_cutoff = std::max(ACInfo.cutoff[center_idx] - 0.3, 0.0); app_log() << "Hybrid orbital representation setting 'inner_cutoff' to " << inner_cutoff << " for group " << my_GroupID << " as atom " << center_idx << std::endl; // overwrite the inner_cutoff of all the atoms of the same species for (int id = 0; id < ACInfo.Ncenters; id++) if (my_GroupID == ACInfo.GroupID[id]) ACInfo.inner_cutoff[id] = inner_cutoff; } else if (ACInfo.inner_cutoff[center_idx] > ACInfo.cutoff[center_idx]) { app_error() << "Hybrid orbital representation 'inner_cutoff' must be smaller than 'spline_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.cutoff[center_idx] > 0) { if (ACInfo.lmax[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'lmax' for atom " << center_idx << std::endl; success = false; } if (ACInfo.spline_radius[center_idx] < 0 && ACInfo.spline_npoints[center_idx] < 0) { app_log() << "Parameters 'spline_radius' and 'spline_npoints' for group " << my_GroupID << " as atom " << center_idx << " are not specified." << std::endl; const double delta = std::min(0.02, ACInfo.cutoff[center_idx] / 4.0); const int n_grid_point = std::ceil((ACInfo.cutoff[center_idx] + 1e-4) / delta) + 3; for (int id = 0; id < ACInfo.Ncenters; id++) if (my_GroupID == ACInfo.GroupID[id]) { ACInfo.spline_npoints[id] = n_grid_point; ACInfo.spline_radius[id] = (n_grid_point - 1) * delta; } app_log() << " Based on default grid point distance " << delta << std::endl; app_log() << " Setting 'spline_npoints' to " << ACInfo.spline_npoints[center_idx] << std::endl; app_log() << " Setting 'spline_radius' to " << ACInfo.spline_radius[center_idx] << std::endl; } else { if (ACInfo.spline_radius[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'spline_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.spline_npoints[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'spline_npoints' for atom " << center_idx << std::endl; success = false; } } // check maximally allowed cutoff_radius double max_allowed_cutoff = ACInfo.spline_radius[center_idx] - 2.0 * ACInfo.spline_radius[center_idx] / (ACInfo.spline_npoints[center_idx] - 1); if (success && ACInfo.cutoff[center_idx] > max_allowed_cutoff) { app_error() << "Hybrid orbital representation requires cutoff_radius<=" << max_allowed_cutoff << " calculated by spline_radius-2*spline_radius/(spline_npoints-1) for atom " << center_idx << std::endl; success = false; } } else { // no atomic regions for this atom type ACInfo.spline_radius[center_idx] = 0.0; ACInfo.spline_npoints[center_idx] = 0; ACInfo.lmax[center_idx] = 0; } } if (!success) BaseReader::myComm->barrier_and_abort("initialize_hybridrep_atomic_centers Failed to initialize atomic centers " "in hybrid orbital representation!"); for (int center_idx = 0; center_idx < ACInfo.Ncenters; center_idx++) { AtomicOrbitals<DataType> oneCenter(ACInfo.lmax[center_idx]); oneCenter.set_info(ACInfo.ion_pos[center_idx], ACInfo.cutoff[center_idx], ACInfo.inner_cutoff[center_idx], ACInfo.spline_radius[center_idx], ACInfo.non_overlapping_radius[center_idx], ACInfo.spline_npoints[center_idx]); centers.push_back(oneCenter); } } } /** initialize construct atomic orbital radial functions from plane waves */ inline void create_atomic_centers_Gspace(Vector<std::complex<double>>& cG, Communicate& band_group_comm, int iorb) override { band_group_comm.bcast(rotate_phase_r); band_group_comm.bcast(rotate_phase_i); band_group_comm.bcast(cG); //distribute G-vectors over processor groups const int Ngvecs = mybuilder->Gvecs[0].size(); const int Nprocs = band_group_comm.size(); const int Ngvecgroups = std::min(Ngvecs, Nprocs); Communicate gvec_group_comm(band_group_comm, Ngvecgroups); std::vector<int> gvec_groups(Ngvecgroups + 1, 0); FairDivideLow(Ngvecs, Ngvecgroups, gvec_groups); const int gvec_first = gvec_groups[gvec_group_comm.getGroupID()]; const int gvec_last = gvec_groups[gvec_group_comm.getGroupID() + 1]; // prepare Gvecs Ylm(G) typedef typename EinsplineSetBuilder::UnitCellType UnitCellType; Gvectors<double, UnitCellType> Gvecs(mybuilder->Gvecs[0], mybuilder->PrimCell, bspline->HalfG, gvec_first, gvec_last); // if(band_group_comm.isGroupLeader()) std::cout << "print band=" << iorb << " KE=" << Gvecs.evaluate_KE(cG) << std::endl; std::vector<AtomicOrbitals<DataType>>& centers = bspline->AtomicCenters; app_log() << "Transforming band " << iorb << " on Rank 0" << std::endl; // collect atomic centers by group std::vector<int> uniq_species; for (int center_idx = 0; center_idx < centers.size(); center_idx++) { auto& ACInfo = mybuilder->AtomicCentersInfo; const int my_GroupID = ACInfo.GroupID[center_idx]; int found_idx = -1; for (size_t idx = 0; idx < uniq_species.size(); idx++) if (my_GroupID == uniq_species[idx]) { found_idx = idx; break; } if (found_idx < 0) uniq_species.push_back(my_GroupID); } // construct group list std::vector<std::vector<int>> group_list(uniq_species.size()); for (int center_idx = 0; center_idx < centers.size(); center_idx++) { auto& ACInfo = mybuilder->AtomicCentersInfo; const int my_GroupID = ACInfo.GroupID[center_idx]; for (size_t idx = 0; idx < uniq_species.size(); idx++) if (my_GroupID == uniq_species[idx]) { group_list[idx].push_back(center_idx); break; } } for (int group_idx = 0; group_idx < group_list.size(); group_idx++) { const auto& mygroup = group_list[group_idx]; const double spline_radius = centers[mygroup[0]].getSplineRadius(); const int spline_npoints = centers[mygroup[0]].getSplineNpoints(); const int lmax = centers[mygroup[0]].getLmax(); const double delta = spline_radius / static_cast<double>(spline_npoints - 1); const int lm_tot = (lmax + 1) * (lmax + 1); const size_t natoms = mygroup.size(); const int policy = lm_tot > natoms ? 0 : 1; std::vector<std::complex<double>> i_power(lm_tot); // rotate phase is introduced here. std::complex<double> i_temp(rotate_phase_r, rotate_phase_i); for (size_t l = 0; l <= lmax; l++) { for (size_t lm = l * l; lm < (l + 1) * (l + 1); lm++) i_power[lm] = i_temp; i_temp *= std::complex<double>(0.0, 1.0); } std::vector<Matrix<double>> all_vals(natoms); std::vector<std::vector<aligned_vector<double>>> vals_local(spline_npoints * omp_get_max_threads()); VectorSoaContainer<double, 3> myRSoA(natoms); for (size_t idx = 0; idx < natoms; idx++) { all_vals[idx].resize(spline_npoints, lm_tot * 2); all_vals[idx] = 0.0; myRSoA(idx) = centers[mygroup[idx]].getCenterPos(); } #pragma omp parallel { const size_t tid = omp_get_thread_num(); const size_t nt = omp_get_num_threads(); for (int ip = 0; ip < spline_npoints; ip++) { const size_t ip_idx = tid * spline_npoints + ip; if (policy == 1) { vals_local[ip_idx].resize(lm_tot * 2); for (size_t lm = 0; lm < lm_tot * 2; lm++) { auto& vals = vals_local[ip_idx][lm]; vals.resize(natoms); std::fill(vals.begin(), vals.end(), 0.0); } } else { vals_local[ip_idx].resize(natoms * 2); for (size_t iat = 0; iat < natoms * 2; iat++) { auto& vals = vals_local[ip_idx][iat]; vals.resize(lm_tot); std::fill(vals.begin(), vals.end(), 0.0); } } } const size_t size_pw_tile = 32; const size_t num_pw_tiles = (Gvecs.NumGvecs + size_pw_tile - 1) / size_pw_tile; aligned_vector<double> j_lm_G(lm_tot, 0.0); std::vector<aligned_vector<double>> phase_shift_r(size_pw_tile); std::vector<aligned_vector<double>> phase_shift_i(size_pw_tile); std::vector<aligned_vector<double>> YlmG(size_pw_tile); for (size_t ig = 0; ig < size_pw_tile; ig++) { phase_shift_r[ig].resize(natoms); phase_shift_i[ig].resize(natoms); YlmG[ig].resize(lm_tot); } SoaSphericalTensor<double> Ylm(lmax); #pragma omp for for (size_t tile_id = 0; tile_id < num_pw_tiles; tile_id++) { const size_t ig_first = tile_id * size_pw_tile; const size_t ig_last = std::min((tile_id + 1) * size_pw_tile, Gvecs.NumGvecs); for (size_t ig = ig_first; ig < ig_last; ig++) { const size_t ig_local = ig - ig_first; // calculate phase shift for all the centers of this group Gvecs.calc_phase_shift(myRSoA, ig, phase_shift_r[ig_local], phase_shift_i[ig_local]); Gvecs.calc_Ylm_G(ig, Ylm, YlmG[ig_local]); } for (int ip = 0; ip < spline_npoints; ip++) { double r = delta * static_cast<double>(ip); const size_t ip_idx = tid * spline_npoints + ip; for (size_t ig = ig_first; ig < ig_last; ig++) { const size_t ig_local = ig - ig_first; // calculate spherical bessel function Gvecs.calc_jlm_G(lmax, r, ig, j_lm_G); for (size_t lm = 0; lm < lm_tot; lm++) j_lm_G[lm] *= YlmG[ig_local][lm]; const double cG_r = cG[ig + gvec_first].real(); const double cG_i = cG[ig + gvec_first].imag(); if (policy == 1) { for (size_t lm = 0; lm < lm_tot; lm++) { double* restrict vals_r = vals_local[ip_idx][lm * 2].data(); double* restrict vals_i = vals_local[ip_idx][lm * 2 + 1].data(); const double* restrict ps_r_ptr = phase_shift_r[ig_local].data(); const double* restrict ps_i_ptr = phase_shift_i[ig_local].data(); double cG_j_r = cG_r * j_lm_G[lm]; double cG_j_i = cG_i * j_lm_G[lm]; #pragma omp simd aligned(vals_r, vals_i, ps_r_ptr, ps_i_ptr) for (size_t idx = 0; idx < natoms; idx++) { const double ps_r = ps_r_ptr[idx]; const double ps_i = ps_i_ptr[idx]; vals_r[idx] += cG_j_r * ps_r - cG_j_i * ps_i; vals_i[idx] += cG_j_i * ps_r + cG_j_r * ps_i; } } } else { for (size_t idx = 0; idx < natoms; idx++) { double* restrict vals_r = vals_local[ip_idx][idx * 2].data(); double* restrict vals_i = vals_local[ip_idx][idx * 2 + 1].data(); const double* restrict j_lm_G_ptr = j_lm_G.data(); double cG_ps_r = cG_r * phase_shift_r[ig_local][idx] - cG_i * phase_shift_i[ig_local][idx]; double cG_ps_i = cG_i * phase_shift_r[ig_local][idx] + cG_r * phase_shift_i[ig_local][idx]; #pragma omp simd aligned(vals_r, vals_i, j_lm_G_ptr) for (size_t lm = 0; lm < lm_tot; lm++) { const double jlm = j_lm_G_ptr[lm]; vals_r[lm] += cG_ps_r * jlm; vals_i[lm] += cG_ps_i * jlm; } } } } } } #pragma omp for collapse(2) for (int ip = 0; ip < spline_npoints; ip++) for (size_t idx = 0; idx < natoms; idx++) { double* vals = all_vals[idx][ip]; for (size_t tid = 0; tid < nt; tid++) for (size_t lm = 0; lm < lm_tot; lm++) { double vals_th_r, vals_th_i; const size_t ip_idx = tid * spline_npoints + ip; if (policy == 1) { vals_th_r = vals_local[ip_idx][lm * 2][idx]; vals_th_i = vals_local[ip_idx][lm * 2 + 1][idx]; } else { vals_th_r = vals_local[ip_idx][idx * 2][lm]; vals_th_i = vals_local[ip_idx][idx * 2 + 1][lm]; } const double real_tmp = 4.0 * M_PI * i_power[lm].real(); const double imag_tmp = 4.0 * M_PI * i_power[lm].imag(); vals[lm] += vals_th_r * real_tmp - vals_th_i * imag_tmp; vals[lm + lm_tot] += vals_th_i * real_tmp + vals_th_r * imag_tmp; } } } //app_log() << "Building band " << iorb << " at center " << center_idx << std::endl; for (size_t idx = 0; idx < natoms; idx++) { // reduce all_vals band_group_comm.reduce_in_place(all_vals[idx].data(), all_vals[idx].size()); if (!band_group_comm.isGroupLeader()) continue; #pragma omp parallel for for (int lm = 0; lm < lm_tot; lm++) { auto& mycenter = centers[mygroup[idx]]; aligned_vector<double> splineData_r(spline_npoints); UBspline_1d_d* atomic_spline_r; for (size_t ip = 0; ip < spline_npoints; ip++) splineData_r[ip] = all_vals[idx][ip][lm]; atomic_spline_r = einspline::create(atomic_spline_r, 0.0, spline_radius, spline_npoints, splineData_r.data(), ((lm == 0) || (lm > 3))); if (!bspline->is_complex) { mycenter.set_spline(atomic_spline_r, lm, iorb); einspline::destroy(atomic_spline_r); } else { aligned_vector<double> splineData_i(spline_npoints); UBspline_1d_d* atomic_spline_i; for (size_t ip = 0; ip < spline_npoints; ip++) splineData_i[ip] = all_vals[idx][ip][lm + lm_tot]; atomic_spline_i = einspline::create(atomic_spline_i, 0.0, spline_radius, spline_npoints, splineData_i.data(), ((lm == 0) || (lm > 3))); mycenter.set_spline(atomic_spline_r, lm, iorb * 2); mycenter.set_spline(atomic_spline_i, lm, iorb * 2 + 1); einspline::destroy(atomic_spline_r); einspline::destroy(atomic_spline_i); } } } #ifdef PRINT_RADIAL char fname[64]; sprintf(fname, "band_%d_center_%d_pw.dat", iorb, center_idx); FILE* fout_pw = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_v.dat", iorb, center_idx); FILE* fout_spline_v = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_g.dat", iorb, center_idx); FILE* fout_spline_g = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_l.dat", iorb, center_idx); FILE* fout_spline_l = fopen(fname, "w"); fprintf(fout_pw, "# r vals(lm)\n"); fprintf(fout_spline_v, "# r vals(lm)\n"); fprintf(fout_spline_g, "# r grads(lm)\n"); fprintf(fout_spline_l, "# r lapls(lm)\n"); // write to file for plotting for (int ip = 0; ip < spline_npoints - 1; ip++) { double r = delta * static_cast<double>(ip); mycenter.SplineInst->evaluate_vgl(r, mycenter.localV, mycenter.localG, mycenter.localL); fprintf(fout_pw, "%15.10lf ", r); fprintf(fout_spline_v, "%15.10lf ", r); fprintf(fout_spline_g, "%15.10lf ", r); fprintf(fout_spline_l, "%15.10lf ", r); for (int lm = 0; lm < lm_tot; lm++) { fprintf(fout_pw, "%15.10lf %15.10lf ", all_vals[center_idx][ip][lm].real(), all_vals[center_idx][ip][lm].imag()); fprintf(fout_spline_v, "%15.10lf %15.10lf ", mycenter.localV[lm * mycenter.Npad + iorb * 2], mycenter.localV[lm * mycenter.Npad + iorb * 2 + 1]); fprintf(fout_spline_g, "%15.10lf %15.10lf ", mycenter.localG[lm * mycenter.Npad + iorb * 2], mycenter.localG[lm * mycenter.Npad + iorb * 2 + 1]); fprintf(fout_spline_l, "%15.10lf %15.10lf ", mycenter.localL[lm * mycenter.Npad + iorb * 2], mycenter.localL[lm * mycenter.Npad + iorb * 2 + 1]); } fprintf(fout_pw, "\n"); fprintf(fout_spline_v, "\n"); fprintf(fout_spline_g, "\n"); fprintf(fout_spline_l, "\n"); } fclose(fout_pw); fclose(fout_spline_v); fclose(fout_spline_g); fclose(fout_spline_l); #endif } } }; } // namespace qmcplusplus #endif
Q5.1.c
/* File: histogram.c * Purpose: Build a histogram from some random data * * Compile: gcc -g -Wall -o histogram histogram.c * Run: ./histogram <bin_count> <min_meas> <max_meas> <data_count> * * Input: None * Output: A histogram with X's showing the number of measurements * in each bin * * Notes: * 1. Actual measurements y are in the range min_meas <= y < max_meas * 2. bin_counts[i] stores the number of measurements x in the range * 3. bin_maxes[i-1] <= x < bin_maxes[i] (bin_maxes[-1] = min_meas) * 4. DEBUG compile flag gives verbose output * 5. The program will terminate if either the number of command line * arguments is incorrect or if the search for a bin for a * measurement fails. * * IPP: Section 2.7.1 (pp. 66 and ff.) */ #include <stdio.h> #include <stdlib.h> #include <omp.h> int thread_count; void Usage(char prog_name[]); void Get_args( char* argv[] /* in */, int* bin_count_p /* out */, float* min_meas_p /* out */, float* max_meas_p /* out */, int* data_count_p /* out */, int* thread_count); void Gen_data( float min_meas /* in */, float max_meas /* in */, float data[] /* out */, int data_count /* in */); void Gen_bins( float min_meas /* in */, float max_meas /* in */, float bin_maxes[] /* out */, int bin_counts[] /* out */, int bin_count /* in */); int Which_bin( float data /* in */, float bin_maxes[] /* in */, int bin_count /* in */, float min_meas /* in */); void Print_histo( float bin_maxes[] /* in */, int bin_counts[] /* in */, int bin_count /* in */, float min_meas /* in */); int main(int argc, char* argv[]) { int bin_count, i, bin; float min_meas, max_meas; float* bin_maxes; int* bin_counts; int data_count; float* data; /* Check and get command line args */ if (argc != 6) Usage(argv[0]); Get_args(argv, &bin_count, &min_meas, &max_meas, &data_count, &thread_count); /* Allocate arrays needed */ bin_maxes = malloc(bin_count*sizeof(float)); bin_counts = malloc(bin_count*sizeof(int)); data = malloc(data_count*sizeof(float)); /* Generate the data */ Gen_data(min_meas, max_meas, data, data_count); /* Create bins for storing counts */ Gen_bins(min_meas, max_meas, bin_maxes, bin_counts, bin_count); /* Count number of values in each bin */ #pragma omp parallel for num_threads(thread_count) default(none) \ shared(data_count, data, bin_maxes, bin_count, min_meas, bin_counts) \ private(bin, i) for (i = 0; i < data_count; i++) { bin = Which_bin(data[i], bin_maxes, bin_count, min_meas); #pragma omp critical bin_counts[bin]++; } # ifdef DEBUG printf("bin_counts = "); for (i = 0; i < bin_count; i++) printf("%d ", bin_counts[i]); printf("\n"); # endif /* Print the histogram */ Print_histo(bin_maxes, bin_counts, bin_count, min_meas); free(data); free(bin_maxes); free(bin_counts); return 0; } /* main */ /*--------------------------------------------------------------------- * Function: Usage * Purpose: Print a message showing how to run program and quit * In arg: prog_name: the name of the program from the command line */ void Usage(char prog_name[] /* in */) { fprintf(stderr, "usage: %s ", prog_name); fprintf(stderr, "<bin_count> <min_meas> <max_meas> <data_count> <thread_count>\n"); exit(0); } /* Usage */ /*--------------------------------------------------------------------- * Function: Get_args * Purpose: Get the command line arguments * In arg: argv: strings from command line * Out args: bin_count_p: number of bins * min_meas_p: minimum measurement * max_meas_p: maximum measurement * data_count_p: number of measurements */ void Get_args( char* argv[] /* in */, int* bin_count_p /* out */, float* min_meas_p /* out */, float* max_meas_p /* out */, int* data_count_p /* out */, int* thread_count) { *bin_count_p = strtol(argv[1], NULL, 10); *min_meas_p = strtof(argv[2], NULL); *max_meas_p = strtof(argv[3], NULL); *data_count_p = strtol(argv[4], NULL, 10); *thread_count = strtol(argv[5], NULL, 10); # ifdef DEBUG printf("bin_count = %d\n", *bin_count_p); printf("min_meas = %f, max_meas = %f\n", *min_meas_p, *max_meas_p); printf("data_count = %d\n", *data_count_p); # endif } /* Get_args */ /*--------------------------------------------------------------------- * Function: Gen_data * Purpose: Generate random floats in the range min_meas <= x < max_meas * In args: min_meas: the minimum possible value for the data * max_meas: the maximum possible value for the data * data_count: the number of measurements * Out arg: data: the actual measurements */ void Gen_data( float min_meas /* in */, float max_meas /* in */, float data[] /* out */, int data_count /* in */) { int i; srandom(0); #pragma omp parallel for num_threads(thread_count) \ default(none) shared(data, min_meas, max_meas, data_count) for (i = 0; i < data_count; i++) { data[i] = min_meas + (max_meas - min_meas) * random() / ((double) RAND_MAX); } # ifdef DEBUG printf("data = "); for (i = 0; i < data_count; i++) printf("%4.3f ", data[i]); printf("\n"); # endif } /* Gen_data */ /*--------------------------------------------------------------------- * Function: Gen_bins * Purpose: Compute max value for each bin, and store 0 as the * number of values in each bin * In args: min_meas: the minimum possible measurement * max_meas: the maximum possible measurement * bin_count: the number of bins * Out args: bin_maxes: the maximum possible value for each bin * bin_counts: the number of data values in each bin */ void Gen_bins( float min_meas /* in */, float max_meas /* in */, float bin_maxes[] /* out */, int bin_counts[] /* out */, int bin_count /* in */) { float bin_width; int i; bin_width = (max_meas - min_meas)/bin_count; #pragma omp parallel for num_threads(thread_count) \ default(none) \ shared(min_meas, max_meas, bin_maxes, bin_counts, bin_count, bin_width) \ private(i) for (i = 0; i < bin_count; i++) { bin_maxes[i] = min_meas + (i+1)*bin_width; bin_counts[i] = 0; } # ifdef DEBUG printf("bin_maxes = "); for (i = 0; i < bin_count; i++) printf("%4.3f ", bin_maxes[i]); printf("\n"); # endif } /* Gen_bins */ /*--------------------------------------------------------------------- * Function: Which_bin * Purpose: Use binary search to determine which bin a measurement * belongs to * In args: data: the current measurement * bin_maxes: list of max bin values * bin_count: number of bins * min_meas: the minimum possible measurement * Return: the number of the bin to which data belongs * Notes: * 1. The bin to which data belongs satisfies * * bin_maxes[i-1] <= data < bin_maxes[i] * * where, bin_maxes[-1] = min_meas * 2. If the search fails, the function prints a message and exits */ int Which_bin( float data /* in */, float bin_maxes[] /* in */, int bin_count /* in */, float min_meas /* in */) { int bottom = 0, top = bin_count-1; int mid; float bin_max, bin_min; while (bottom <= top) { mid = (bottom + top)/2; bin_max = bin_maxes[mid]; bin_min = (mid == 0) ? min_meas: bin_maxes[mid-1]; if (data >= bin_max) bottom = mid+1; else if (data < bin_min) top = mid-1; else return mid; } /* Whoops! */ fprintf(stderr, "Data = %f doesn't belong to a bin!\n", data); fprintf(stderr, "Quitting\n"); exit(-1); } /* Which_bin */ /*--------------------------------------------------------------------- * Function: Print_histo * Purpose: Print a histogram. The number of elements in each * bin is shown by an array of X's. * In args: bin_maxes: the max value for each bin * bin_counts: the number of elements in each bin * bin_count: the number of bins * min_meas: the minimum possible measurment */ void Print_histo( float bin_maxes[] /* in */, int bin_counts[] /* in */, int bin_count /* in */, float min_meas /* in */) { int i, j; float bin_max, bin_min; for (i = 0; i < bin_count; i++) { bin_max = bin_maxes[i]; bin_min = (i == 0) ? min_meas: bin_maxes[i-1]; printf("%.3f-%.3f:\t", bin_min, bin_max); for (j = 0; j < bin_counts[i]; j++) printf("X"); printf("\n"); } } /* Print_histo */
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
GB_unop__identity_bool_uint64.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_bool_uint64) // op(A') function: GB (_unop_tran__identity_bool_uint64) // C type: bool // A type: uint64_t // cast: bool cij = (bool) aij // unaryop: cij = aij #define GB_ATYPE \ uint64_t #define GB_CTYPE \ bool // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ bool z = (bool) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ bool z = (bool) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_BOOL || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_bool_uint64) ( bool *Cx, // Cx and Ax may be aliased const uint64_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++) { uint64_t aij = Ax [p] ; bool z = (bool) 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 ; uint64_t aij = Ax [p] ; bool z = (bool) 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_bool_uint64) ( 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
rnn_helpers.h
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #pragma once #ifdef _WIN32 #pragma warning(disable : 4267) #endif #include <algorithm> #include <functional> #include <future> #include <string> #include <vector> #include "gsl/span" #include "gsl/gsl_algorithm" #include "core/common/common.h" #include "core/common/logging/logging.h" #include "core/framework/allocator.h" #include "core/util/math.h" #include "core/util/math_cpuonly.h" #ifdef USE_EIGEN_THREADPOOL #include <unsupported/Eigen/CXX11/ThreadPool> #else #include "core/common/task_thread_pool.h" #endif namespace onnxruntime { class Tensor; class OpKernelContext; namespace rnn { namespace detail { enum Direction { kForward = 0, kReverse = 1, kBidirectional = 2 }; inline Direction MakeDirection(const std::string& direction) { if (direction == "forward") { return kForward; } else if (direction == "reverse") { return kReverse; } else if (direction == "bidirectional") { return kBidirectional; } else { ORT_THROW("Invalid 'direction' argument of '", direction, "'. Must be one of 'forward', 'reverse', or 'bidirectional'."); } } /** Allocate a unique_ptr using allocator_, and return a span to the allocated memory so usage is safe @param allocator IAllocator to use for the allocation. @param size Allocation size. Number of elements of type TAlloc, or total size if TAlloc is 'void'. @param unique_ptr unique_ptr that will control the lifetime of the allocated memory. @param fill If true, fill the allocated memory with fill_value. @param fill_value Value to use if 'fill' is true. @returns A span to provide bounds checked access to the allocated memory. */ template <typename TAlloc> gsl::span<TAlloc> Allocate(std::shared_ptr<IAllocator> allocator, size_t size, IAllocatorUniquePtr<TAlloc>& unique_ptr, bool fill = false, TAlloc fill_value = TAlloc{}) { unique_ptr = IAllocator::MakeUniquePtr<TAlloc>(allocator, size); auto span = gsl::make_span(unique_ptr.get(), size); if (fill) { // Do't use span.begin() it will cause performance issue and stop compiler to optimize the code std::fill_n(unique_ptr.get(), size, fill_value); } return span; } // validate the common inputs to RNN, LSTM and GRU operators Status ValidateCommonRnnInputs(const Tensor& X, const Tensor& W, const Tensor& R, const Tensor* B, int WRB_dim_1_multipler, // multiplier used with hidden_size for W, R and B inputs const Tensor* sequence_lens, const Tensor* initial_h, int64_t num_directions, int64_t hidden_size); /// Copy an input array repeatedly to an output array /// @param input_begin Beginning of input /// @param input_end End of input /// @param output Output iterator /// @param repetitions Number of times to repeat copy. Assumes output is sufficiently sized. /// @returns Position of output iterator after copy is completed template <typename TInIter, typename TOutIter> TOutIter RepeatVectorToConstructArray(TInIter input_begin, TInIter input_end, TOutIter output, int64_t repetitions) { for (int64_t i = 0; i < repetitions; i++) { output = std::copy(input_begin, input_end, output); } return output; } // reverse an LSTM or GRU sequence which has shape [seq_length, batch_size, hidden_size] // and output to shape [seq_length, num_directions, batch_size, hidden_size] template <typename T> void ReverseSequence(gsl::span<const T> inputs, gsl::span<T> inputs_reverse, gsl::span<const int> sequence_lengths, const int max_sequence_length, const int batch_size, const int input_size, const int num_directions) { for (int i = 0; i < batch_size; i++) { int seq_len = sequence_lengths[i]; if (seq_len == 0) continue; #ifdef USE_OPENMP // Parallel execute the loop. #pragma omp parallel for #endif for (int j = 0; j < seq_len; j++) { gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size); gsl::span<T> dest = inputs_reverse.subspan(num_directions * (seq_len - j - 1) * batch_size * input_size + i * input_size, input_size); // Use gsl::copy instead of std::copy() to allow compiler to optimize the code gsl::copy(src, dest); } #ifdef USE_OPENMP // Parallel execute the loop. #pragma omp parallel for #endif for (int j = seq_len; j < max_sequence_length; j++) { gsl::span<const T> src = inputs.subspan(j * batch_size * input_size + i * input_size, input_size); gsl::span<T> dest = inputs_reverse.subspan(num_directions * j * batch_size * input_size + i * input_size, input_size); // Use gsl::copy instead of std::copy() to allow compiler to optimize the code gsl::copy(src, dest); } } } // A has size M x K, B has size N x K (transposed), and C has size M x N // We check that A, B and C are large enough before calling the lower level GEMM implementation template <typename TSpanAIter, typename TSpanBIter, typename TSpanCIter> void ComputeGemm(const int M, const int N, const int K, const float alpha, TSpanAIter A, TSpanAIter A_end, const int lda, TSpanBIter B, TSpanBIter B_end, const int ldb, const float beta, TSpanCIter C, TSpanCIter C_end, const int ldc) { // validate all the inputs // need to use the lda/ldb/ldc strides which should be >= the columns for the span ORT_ENFORCE(lda >= K && ldb >= K && ldc >= N); ORT_ENFORCE(A + (M * lda - (lda - K)) <= A_end); ORT_ENFORCE(B + (N * ldb - (ldb - K)) <= B_end); ORT_ENFORCE(C + (M * ldc - (ldc - N)) <= C_end); ::onnxruntime::math::GemmEx<float, CPUMathUtil>( CblasNoTrans, CblasTrans, M, N, K, alpha, &*A, lda, &*B, ldb, beta, &*C, ldc, &CPUMathUtil::Instance()); } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> const T* SafeRawConstPointer(typename gsl::span<T>::const_iterator cur, typename gsl::span<T>::const_iterator end, size_t size) { ORT_ENFORCE(cur + size <= end); return &*cur; } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> const T* SafeRawConstPointer(gsl::span<T> span, size_t offset, size_t size) { ORT_ENFORCE(offset + size <= size_t(span.size())); return span.data(); } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> T* SafeRawPointer(typename gsl::span<T>::iterator cur, typename gsl::span<T>::iterator end, size_t size) { ORT_ENFORCE(cur + size <= end); return &*cur; } // helper to convert a span to a raw pointer // after validating the memory covered by the span supports the size required template <typename T> T* SafeRawPointer(typename gsl::span<T> span, size_t offset, size_t size) { ORT_ENFORCE(offset + size <= size_t(span.size())); return span.data() + offset; } template <typename TLambda> void ExecuteLambdaInParallel(const std::string& name, TLambda lambda, int max, int step, #ifdef USE_EIGEN_THREADPOOL Eigen::NonBlockingThreadPool& ttp, #else TaskThreadPool& ttp, #endif const ::onnxruntime::logging::Logger& logger) { // #define NOTHREADS to execute the lambdas directly and in order if you need to do that to debug #ifdef NOTHREADS ORT_UNUSED_PARAMETER(ttp); ORT_UNUSED_PARAMETER(logger); for (int i = 0; i < max; i += step) { (void)name; std::bind(lambda, i)(); } #else #ifdef USE_EIGEN_THREADPOOL ORT_UNUSED_PARAMETER(name); ORT_UNUSED_PARAMETER(logger); std::atomic<int> done(0); for (int i = 0; i < max; i += step) { ttp.Schedule([lambda, i, &done]() { lambda(i); ++done; }); } int totalTasks = (int)max / (step > 0 ? step : 1) + (max % step > 0 ? 1 : 0); while (done != totalTasks) { } #else std::vector<std::future<void> > task_results{}; task_results.reserve(static_cast<size_t>(std::ceil(max / step))); for (int i = 0; i < max; i += step) { std::packaged_task<void()> task{std::bind(lambda, i)}; task_results.emplace_back(task.get_future()); ttp.RunTask(std::move(task)); } try { // wait for all and propagate any exceptions for (auto& future : task_results) future.get(); } catch (const std::exception& ex) { LOGS(logger, ERROR) << name << " - exception running tasks: " << ex.what(); throw; } #endif // else part of #ifdef USE_EIGEN_THREADPOOLs #endif // else part of #ifdef NOTHREADS } void DumpMatrixImpl(const std::string& name, const float* src, int row, int col, int offset = 0, int col_width = -1); // Helper class to wrap the processing of the activation funcs and any alpha/beta values. // The alpha/beta values are consumed in the order of the activation funcs. once they run out // defaults will be used as needed. // The Entries property contains the normalized function names and the alpha/beta value to use. class ActivationFuncs { public: struct Entry { const std::string name; const float alpha; const float beta; }; ActivationFuncs() = default; ActivationFuncs(const std::vector<std::string>& funcs, const std::vector<float>& alphas, const std::vector<float>& betas); const std::vector<Entry>& Entries() const { return entries_; } private: std::vector<Entry> entries_; }; namespace deepcpu { using AddBiasIntoFuncPtr = void (*)(const float*, float*, const int); using ClipWithBiasFuncPtr = void (*)(const float, const float*, float*, const int); using ActivationFuncPtr = void (*)(float*, const int, const float, const float); using ActivationFuncBPtr = void (*)(const float*, float*, const int, const float, const float); using LstmMergeGatesFuncPtr = void (*)(const float*, float*, const float*, float*, const int, const float, const float); using GruResetGateFuncPtr = void (*)(const float*, float*, float*, const int, const float, const float); using GruOutputGateFuncPtr = void (*)(float*, const float*, const float*, float*, const int, const float, const float); ActivationFuncPtr ActivationFuncByName(const std::string& func); LstmMergeGatesFuncPtr LstmMergeGatesFuncByName(const std::string& func); GruResetGateFuncPtr GruResetGateFuncByName(const std::string& func); GruOutputGateFuncPtr GruOutputGateFuncByName(const std::string& func); void add_bias_into_ignore(const float* ignored, float* pd, const int c); void add_bias_into(const float* ps, float* pd, const int c); void clip(const float b, float* pd, const int c); void clip_add_bias(const float b, const float* pb, float* pd, const int c); void clip_ignore_bias(const float b, const float* pb, float* pd, const int c); void sigmoid_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void tanh_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void relu_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void sigmoid_exact_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void tanh_exact_m(const float* ps1, float* ps1_c, const float* ps2, float* pd, int c, const float alpha, const float beta); void sigmoid(float* pd, int c, const float alpha, const float beta); void tanh(float* pd, int c, const float alpha, const float beta); void relu(float* pd, int c, const float alpha, const float beta); void sigmoid_exact(float* pd, int c, const float alpha, const float beta); void tanh_exact(float* pd, int c, const float alpha, const float beta); void merge_lstm_gates_to_memory(const float* pprev, const float* pi, const float* pf, const float* pg, float* pcurr, const int c); void gru_reset_gate_tanh(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_reset_gate_sigmoid(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_reset_gate_relu(const float* ps1, float* ps2, float* pd, const int c, const float alpha, const float beta); void gru_output_gate_tanh(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); void gru_output_gate_sigmoid(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); void gru_output_gate_relu(float* ph, const float* pz, const float* ps, float* po, const int c, const float alpha, const float beta); inline void elementwise_product(const float* op1, const float* op2, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += op1[i] * op2[i]; } inline void elementwise_sum1(const float* src, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += src[i]; } inline void elementwise_sum2(const float* src1, const float* src2, float* dest, const int size) { for (int i = 0; i < size; i++) dest[i] += src1[i] + src2[i]; } } // namespace deepcpu } // namespace detail } // namespace rnn } // namespace onnxruntime
9175.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop #pragma omp parallel for private(i, j) collapse(#P12) schedule(#P9, #P11) num_threads(#P11) #pragma omp target teams distribute #p #p for (i = 1; i < _PB_NI - 1; ++i) { #pragma omp parallel for schedule(dynamic, 28) 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; }
extra_mixed_models.c
// // Created by berg on 03/04/19. // #include "../config/extra_data_config.h" #include "../config_helpers/config_helpers.h" #include "../libraries_common/common_data_structures.h" SET_EXTRA_DATA (set_mixed_model_if_x_less_than) { uint32_t num_active_cells = the_grid->num_active_cells; *extra_data_size = sizeof(uint32_t)*(num_active_cells + 1); uint32_t *mapping = (uint32_t*)malloc(*extra_data_size); struct cell_node ** ac = the_grid->active_cells; real x_limit = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, x_limit, config->config_data, "x_limit"); int i; bool inside; #pragma omp parallel for for (i = 0; i < num_active_cells; i++) { real center_x = ac[i]->center.x; real center_y = ac[i]->center.y; real center_z = ac[i]->center.z; inside = (center_x <= x_limit); if (inside) mapping[i] = 0; else mapping[i] = 1; } return (void*)mapping; } SET_EXTRA_DATA (set_mixed_model_purkinje_if_x_less_than) { uint32_t num_active_purkinje_cells = the_grid->the_purkinje->num_active_purkinje_cells; *extra_data_size = sizeof(uint32_t)*(num_active_purkinje_cells + 1); uint32_t *mapping = (uint32_t*)malloc(*extra_data_size); struct cell_node ** ac_purkinje = the_grid->the_purkinje->purkinje_cells; real x_limit = 0.0; GET_PARAMETER_NUMERIC_VALUE_OR_REPORT_ERROR(real, x_limit, config->config_data, "x_limit"); int i; bool inside; #pragma omp parallel for for (i = 0; i < num_active_purkinje_cells; i++) { real center_x = ac_purkinje[i]->center.x; real center_y = ac_purkinje[i]->center.y; real center_z = ac_purkinje[i]->center.z; inside = (center_x <= x_limit); if (inside) mapping[i] = 0; else mapping[i] = 1; } return (void*)mapping; } SET_EXTRA_DATA (set_mixed_model_purkinje_and_tissue) { uint32_t num_active_tissue_cells = the_grid->num_active_cells; uint32_t num_active_purkinje_cells = the_grid->the_purkinje->num_active_purkinje_cells; uint32_t num_active_cells = num_active_tissue_cells + num_active_purkinje_cells; *extra_data_size = sizeof(uint32_t)*(num_active_cells + 1); uint32_t *mapping = (uint32_t*)malloc(*extra_data_size); struct cell_node ** ac = the_grid->active_cells; struct cell_node ** ac_purkinje = the_grid->the_purkinje->purkinje_cells; int i; bool inside; // Purkinje section #pragma omp parallel for for (i = 0; i < num_active_purkinje_cells; i++) { mapping[i] = 0; } // Tissue section #pragma omp parallel for for (i = num_active_purkinje_cells; i < num_active_cells; i++) { mapping[i] = 1; } return (void*)mapping; }
l7_setup.c
/* * Copyright (c) 2011-2012, Los Alamos National Security, LLC. * All rights Reserved. * * Copyright 2011-2012. Los Alamos National Security, LLC. This software was produced * under U.S. Government contract DE-AC52-06NA25396 for Los Alamos National * Laboratory (LANL), which is operated by Los Alamos National Security, LLC * for the U.S. Department of Energy. The U.S. Government has rights to use, * reproduce, and distribute this software. NEITHER THE GOVERNMENT NOR LOS * ALAMOS NATIONAL SECURITY, LLC MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR * ASSUMES ANY LIABILITY FOR THE USE OF THIS SOFTWARE. If software is modified * to produce derivative works, such modified software should be clearly marked, * so as not to confuse it with the version available from LANL. * * Additionally, 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 Los Alamos National Security, LLC, Los Alamos * National Laboratory, LANL, the U.S. Government, 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS NATIONAL * SECURITY, LLC 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 "l7.h" #include "l7p.h" #include <stdlib.h> #define L7_LOCATION "L7_SETUP" int L7_Setup( const int num_base, const int my_start_index, const int num_indices_owned, int *indices_needed, const int num_indices_needed, int *l7_id ) { /* Purpose * ======= * L7_Setup is used to setup the update/scatter database as * defined by the global indexing scheme. Each process passes * in parameters which define the indices it owns (i.e. as * defined by 'my_start_index' and 'num_indices_owned') and * lists the indices it needs ('indices_needed'). From this, * a database is defined that allows subsequent calls to * L7_Update. * * Notes: * ====== * 1) Assumes a global indexing set, linearly decomposed across * all processes. * * Arguments * ========= * num_base (input) const L7_INT * global indexing set starts with 1 (Fortran) * or with 0 (C) * * my_start_index (input) const L7_INT * Starting index number of calling process * in global indexing set. * * num_indices_owned (input) const L7_INT * Number of indices owned by calling process. * * indices_needed (input) const L7_INT* * Array containing indices needed by * calling process. * * num_indices_needed (input) const L7_INT * Number of indices of interest listed * in array 'num_indices_needed'. * * l7_id (input/output) int* * Handle to database to be setup. * * 0: L7 sets up a new database, and * assigns it a value. * > 0: L7 resets existing database with * input information. That is, it reuses * the allocated memory. * < 0: An error is returned. * * Notes: * ===== * 1) The handling of 0-based arrays for C and 1-based arrays for Fortran * is handled in L7_Setup. This is done by taking the input global * indices stored in 'indices_global_to_send' and converting them to * 1-based and storing them in 'indices_local_to_send'. * * 2) The indices are handled as 4-byte integers. * * 3) Serial compilation creates a no-op. * * Program Flow * ============ * 0) Check input for basic validity. * 1) Set communication parameters within database. * 2) Deternine processes this pe receives from. * 3) Determine the number of processes this pe sends to. * 4) Send number of as well as the indices needed from each sending process. * 5) Set up array containing the pes this pe sends indices to. * 6) Set up array containing the indices this pe sends to others. */ /* * Local variables. */ int ierr; /* Error code for return */ #ifdef HAVE_MPI int base_adj, /* 0 or 1 based arrays adjustment */ count_total, i, j, /* Counters */ max_sizeof_type, num_msgs, /* Number of sends and recvs needed */ numpes, /* Alias for l7_id_db.numpes. */ num_indices_acctd_for, num_outstanding_requests = 0, num_sends, offset, penum, /* Alias for l7_id_db.penum. */ *pi4_in, /* (int *)l7.receive_buffer */ *pi4_out, /* (int *)l7.send_buffer */ send_buffer_bytes_needed, /* Buffer space requirement. */ start_indices_needed, this_index; /* Offset into indexing set. */ l7_id_database *l7_id_db; MPI_Request *mpi_request; /* Local alias for l7_id_db->mpi_request. */ MPI_Status *mpi_status; /* Local alias for l7_id_db->mpi_status. */ #if defined (_L7_DEBUG) int k; /* Counter */ #endif /* * Executable Statements */ if (! l7.mpi_initialized){ return(0); } if (l7.initialized != 1){ ierr = -1; L7_ASSERT( l7.initialized == 1, "L7 not initialized", ierr); } /* * Check input */ if (num_base){ base_adj = 1; } else { base_adj = 0; } if (my_start_index < 0){ ierr = -1; L7_ASSERT( my_start_index >= 0, "my_start_index < 0", ierr); } if (num_indices_owned < 0){ ierr = -1; L7_ASSERT( num_indices_owned >= 0, "num_indices_owned < 0", ierr); } if (num_indices_needed > 0){ if (indices_needed == NULL){ ierr = -1; L7_ASSERT( (int *)indices_needed != NULL, "indices_needed == NULL", ierr); } } if (*l7_id < 0){ ierr = *l7_id; L7_ASSERT( *l7_id >=0, "L7 Id must be either 0 (new id) or > 0 (existing id)", ierr); } /* * Setup database structure. */ if (*l7_id != 0){ /* * Find it in the database and update based on new input. */ if (l7.first_db == NULL){ L7_ASSERT(l7.first_db != NULL, "Uninitialized l7_id input, but no ids in database", ierr); } l7_id_db = l7.first_db; while (l7_id_db){ if (l7_id_db->l7_id == *l7_id) break; l7_id_db = l7_id_db->next_db; } if (l7.first_db == NULL){ ierr = -1; L7_ASSERT( l7.first_db != NULL, "Uninitialized l7_id input, but not found in this list", ierr); } } else{ /* * Allocate new database, insert into linked list. */ if (l7.num_dbs >= L7_MAX_NUM_DBS){ ierr = -1; L7_ASSERT(l7.num_dbs < L7_MAX_NUM_DBS, "Too many L7 databases allocataed", ierr); } l7_id_db = (l7_id_database*)calloc(1L, sizeof(l7_id_database) ); if (l7_id_db == NULL){ ierr = -1; L7_ASSERT( l7_id_db != NULL, "Failed to allocate new database", ierr); } if ( !(l7.first_db) ){ l7.first_db = l7_id_db; l7.last_db = l7_id_db; l7_id_db->next_db = NULL; /* Paranoia */ l7_id_db->l7_id = 1; l7.num_dbs = 1; } else{ /* * Assign a l7_id. */ l7_id_db->l7_id = l7.last_db->l7_id + 1; /* * Reset links. */ l7.last_db->next_db = l7_id_db; l7.last_db = l7_id_db; l7.num_dbs++; } *l7_id = l7_id_db->l7_id; /* * Initialize some parameters. */ l7_id_db->recv_counts_len = 0; l7_id_db->recv_from_len = 0; l7_id_db->send_to_len = 0; l7_id_db->send_counts_len = 0; l7_id_db->indices_to_send_len = 0; l7_id_db->mpi_request_len = 0; l7_id_db->mpi_status_len = 0; } /* * Store input in database. */ l7_id_db->my_start_index = my_start_index; l7_id_db->num_indices_owned = num_indices_owned; if ( (l7_id_db->indices_needed_len < num_indices_needed ) && (num_indices_needed > 0) ){ if (l7_id_db->indices_needed) free(l7_id_db->indices_needed); l7_id_db->indices_needed = (int *)calloc((unsigned long long)num_indices_needed, sizeof(int) ); if (l7_id_db->indices_needed == NULL){ ierr = -1; L7_ASSERT( (int*)(l7_id_db->indices_needed) != NULL, "Memory failure for indices_needed", ierr); } l7_id_db->indices_needed_len = num_indices_needed; } #ifdef _OPENMP #pragma omp parallel for #endif for (i=0; i<num_indices_needed; i++){ l7_id_db->indices_needed[i] = indices_needed[i]; } l7_id_db->num_indices_needed = num_indices_needed; ierr = MPI_Comm_rank (MPI_COMM_WORLD, &l7_id_db->penum ); L7_ASSERT( ierr == MPI_SUCCESS, "MPI_Comm_rank", ierr); ierr = MPI_Comm_size (MPI_COMM_WORLD, &l7_id_db->numpes ); L7_ASSERT( ierr == MPI_SUCCESS, "MPI_Comm_size", ierr); l7.penum = l7_id_db->penum; /* Local shorthand */ numpes = l7_id_db->numpes; penum = l7_id_db->penum; if (numpes == 1){ return(0); } /* * Create array containing starting (global) index numbers * for all processes. * * 1) Allgather num_indices_owned. * 2) Scan to create starting_index. * 3) Shift all array elements up 1 position. * 4) Set starting_indices[0] = 0. * * The latter two steps allows arrays to be used as below. */ l7_id_db->starting_indices = (int *)calloc((unsigned long long)(numpes+1), sizeof(int)); if(l7_id_db->starting_indices == NULL){ ierr = -1; L7_ASSERT(l7_id_db->starting_indices != NULL, "No memory for l7_id_db->starting_indices", ierr); } ierr = MPI_Allgather( &(l7_id_db->num_indices_owned), 1, MPI_INT, &(l7_id_db->starting_indices[1]), 1, MPI_INT, MPI_COMM_WORLD); L7_ASSERT( ierr == MPI_SUCCESS, "MPI_Allgather (num_indices_owned)", ierr); l7_id_db->starting_indices[0] = 0; // l7_id_db->starting_indices[0] = 1; for (i=0; i<numpes; i++) l7_id_db->starting_indices[i+1] += l7_id_db->starting_indices[i]; /* * Determine the number of processes this pe receives from. */ l7_id_db->num_recvs = 0; start_indices_needed = -1; this_index = 0; if (num_indices_needed > 0){ for (j=0; j<numpes; j++){ if ( indices_needed[this_index] >= l7_id_db->starting_indices[j]){ if (indices_needed[this_index] < l7_id_db->starting_indices[j+1]){ l7_id_db->num_recvs++; #if defined _L7_DEBUG printf("[pe %d] Found first one on pe %d. \n", penum, j); #endif /* Skip through all the rest on pe j. */ /* SKG - Update order to silence valgrind. Don't know if * this is okay... */ while ( ( this_index < num_indices_needed) && ( indices_needed[this_index] < l7_id_db->starting_indices[j+1] ) ) this_index++; /* Remember where we found the first one. */ if ( start_indices_needed == -1) start_indices_needed = j; if (this_index == num_indices_needed) break; } } } if (l7_id_db->num_recvs == 0){ ierr = -1; L7_ASSERT(l7_id_db->num_recvs != 0, "No indices found", ierr); } } if (this_index != num_indices_needed){ printf("[pe %d] ERROR -- can't find all the indices I need. I have %d, need %d\n", penum, this_index, num_indices_needed); } #if defined _L7_DEBUG printf("[pe %d] l7_id_dp->num_recvs = %d\n", penum, l7_id_db->num_recvs); #endif /* * Allocate space for counts for each pe sending to this one. */ if (l7_id_db->num_recvs > l7_id_db->recv_counts_len){ if (l7_id_db->recv_counts) free(l7_id_db->recv_counts); l7_id_db->recv_counts = (int *)calloc((unsigned long long)l7_id_db->num_recvs, sizeof(int) ); if (l7_id_db->recv_counts == NULL){ ierr = -1; L7_ASSERT(l7_id_db->recv_counts != NULL, "No space for l7_id_db->recv_counts", ierr); } l7_id_db->recv_counts_len = l7_id_db->num_recvs; int num_recvs = l7_id_db->num_recvs; // for vectorization #ifdef _OPENMP #pragma omp parallel for #endif for (i=0; i<num_recvs; i++) l7_id_db->recv_counts[i] = 0; /* calloc does not guarantee = 0. */ } if (l7_id_db->num_recvs > l7_id_db->recv_from_len){ if (l7_id_db->recv_from) free(l7_id_db->recv_from); l7_id_db->recv_from = (int *)calloc((unsigned long long)l7_id_db->num_recvs, sizeof(int) ); if (l7_id_db->recv_from == NULL){ ierr = -1; L7_ASSERT(l7_id_db->recv_from != NULL, "No space for l7_id_db->recv_from", ierr); } l7_id_db->recv_from_len = l7_id_db->num_recvs; int num_recvs = l7_id_db->num_recvs; // for vectorization #ifdef _OPENMP #pragma omp parallel for #endif for (i=0; i<num_recvs; i++) l7_id_db->recv_from[i] = -999; } /* * Determine process and the number of indices this pe recvs from it. */ if (num_indices_needed > 0){ this_index = 0; num_indices_acctd_for = 0; i=0; for (j=start_indices_needed; j<numpes; j++){ if (indices_needed[this_index] >= l7_id_db->starting_indices[j] ){ if (indices_needed[this_index] < l7_id_db->starting_indices[j+1]){ /* Found the first one on pe j. */ l7_id_db->recv_from[i] = j; l7_id_db->recv_counts[i] = 1; num_indices_acctd_for++; if (num_indices_acctd_for == num_indices_needed) break; this_index++; /* SKG - Update order to silence valgrind. Don't know if * this is okay... */ while ( ( num_indices_acctd_for < num_indices_needed ) && ( indices_needed[this_index] < l7_id_db->starting_indices[j+1] )) { /* Find the rest on pe j. */ l7_id_db->recv_counts[i]++; this_index++; num_indices_acctd_for++; } if (num_indices_acctd_for == num_indices_needed) break; i++; } } } if (num_indices_needed != num_indices_acctd_for){ ierr = -1; L7_ASSERT(num_indices_needed == num_indices_acctd_for, "Failed to find all the needed indices", ierr); } } /* * Determine number of processes for which this pe owns indices * those pes need. This is done use a reduction (MPI_Allreduce). */ if (l7.sizeof_send_buffer < numpes * (int)sizeof(int)){ if (l7.send_buffer) free(l7.send_buffer); l7.send_buffer = calloc ((unsigned long long)(2*numpes), sizeof(int)); if (l7.send_buffer == NULL){ ierr = -1; L7_ASSERT(l7.send_buffer != NULL, "No memory for send buffer", ierr); } l7.sizeof_send_buffer = 2 * numpes * (int)sizeof(int); } pi4_in = (int*)l7.send_buffer; pi4_out = &pi4_in[numpes]; for (i=0; i<numpes; i++) pi4_in[i] = 0; for (i=0; i<l7_id_db->num_recvs; i++) pi4_in[l7_id_db->recv_from[i]] = 1; ierr = MPI_Allreduce(pi4_in, pi4_out, numpes, MPI_INT, MPI_SUM, MPI_COMM_WORLD); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Allreduce ( l7_id_db->recv_from )", ierr); l7_id_db->num_sends = pi4_out[penum]; #if defined _L7_DEBUG printf("[pe %d] l7_id_db->num_sends = %d \n", penum, l7_id_db->num_sends); #endif /* * Allocate request and status arrays. */ num_msgs = ( 2 * l7_id_db->num_recvs ) + l7_id_db->num_sends; /* Ensure enough outstanding messages for L7_Update_pack model. */ if (num_msgs < (L7_MIN_MPI_REQS * l7_id_db->num_recvs ) ) num_msgs = L7_MIN_MPI_REQS * l7_id_db->num_recvs; if (num_msgs > l7_id_db->mpi_request_len) { if (l7_id_db->mpi_request) free(l7_id_db->mpi_request); l7_id_db->mpi_request = (MPI_Request *) calloc ((unsigned long long)num_msgs, sizeof(MPI_Request)); if (l7_id_db->mpi_request == NULL){ ierr = -1; L7_ASSERT(l7_id_db->mpi_request != NULL, "Allocation of l7_id_db->mpi_request failed", ierr); } l7_id_db->mpi_request_len = num_msgs; } if (num_msgs > l7_id_db->mpi_status_len){ if (l7_id_db->mpi_status) free(l7_id_db->mpi_status); l7_id_db->mpi_status = (MPI_Status *) calloc((unsigned long long)num_msgs, sizeof(MPI_Status) ); if (l7_id_db->mpi_status == NULL){ ierr = -1; L7_ASSERT(l7_id_db->mpi_status != NULL, "Allocation of l7_id_db->mpi_status failed", ierr); } l7_id_db->mpi_status_len = num_msgs; } /* Local shorthand */ mpi_request = l7_id_db->mpi_request; mpi_status = l7_id_db->mpi_status; /* * Send number of indices needed from each sending process. */ num_outstanding_requests = 0; for (i=0; i<l7_id_db->num_recvs; i++){ #if defined _L7_DEBUG printf("[pe %d] recv_counts[%d] = %d to pe %d \n", penum, i, l7_id_db->recv_counts[i], l7_id_db->recv_from[i] ); #endif ierr = MPI_Isend(&l7_id_db->recv_counts[i], 1, MPI_INT, l7_id_db->recv_from[i], L7_SETUP_SEND_COUNT_TAG, MPI_COMM_WORLD, &mpi_request[num_outstanding_requests++] ); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Isend (recv_counts[i] )", ierr); } /* * Receive counts for the processes to which this pe sends. * This pe doesn't know who needs what it has, so we must * use wildcard receives. */ if (l7_id_db->num_sends > l7_id_db->send_counts_len){ if (l7_id_db->send_counts) free(l7_id_db->send_counts); l7_id_db->send_counts = (int *) calloc((unsigned long long)l7_id_db->num_sends, sizeof(int) ); if (l7_id_db->send_counts == NULL){ ierr = -1; L7_ASSERT(l7_id_db->send_counts != NULL, "Failed to allocate l7_id_db->send_counts", ierr); } l7_id_db->send_counts_len = l7_id_db->num_sends; } if (l7_id_db->num_sends > l7_id_db->send_to_len){ if (l7_id_db->send_to) free(l7_id_db->send_to); l7_id_db->send_to = (int *) calloc((unsigned long long)l7_id_db->num_sends, sizeof(int) ); if (l7_id_db->send_to == NULL){ ierr = -1; L7_ASSERT(l7_id_db->send_to != NULL, "Failed to allocate l7_id_db->send_to", ierr); } l7_id_db->send_to_len = l7_id_db->num_sends; } for (i=0; i<l7_id_db->num_sends; i++){ ierr = MPI_Irecv(&l7_id_db->send_counts[i], 1, MPI_INT, MPI_ANY_SOURCE, L7_SETUP_SEND_COUNT_TAG, MPI_COMM_WORLD, &mpi_request[num_outstanding_requests++] ); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Irecv ( indices_needed[i] )", ierr); } if (num_outstanding_requests > 0){ ierr = MPI_Waitall(num_outstanding_requests, mpi_request, mpi_status); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Waitall ( counts )", ierr); } num_outstanding_requests = 0; /* * Determine which processes sent the above messages. * These are the 'send_to' processes. */ offset = l7_id_db->num_recvs; for (i=0; i<l7_id_db->num_sends; i++){ l7_id_db->send_to[i] = mpi_status[offset+i].MPI_SOURCE; } /* * Allocate space for 'indices_global_to_send' and * 'indices_local_to_send'. */ count_total = 0; for (i=0; i<l7_id_db->num_sends; i++){ count_total += l7_id_db->send_counts[i]; } if (count_total > l7_id_db->indices_to_send_len){ if (l7_id_db->indices_global_to_send) free(l7_id_db->indices_global_to_send); l7_id_db->indices_global_to_send = (int *) calloc((unsigned long long)count_total, sizeof(int) ); if (l7_id_db->indices_global_to_send == NULL){ ierr = -1; L7_ASSERT(l7_id_db->indices_global_to_send != NULL, "No memory for l7_id_db->indices_global_to_send.", ierr); } if (l7_id_db->indices_local_to_send) free(l7_id_db->indices_local_to_send); l7_id_db->indices_local_to_send = (int *) calloc((unsigned long long)count_total, sizeof(int) ); if (l7_id_db->indices_local_to_send == NULL){ ierr = -1; L7_ASSERT(l7_id_db->indices_local_to_send != NULL, "No memory for l7_id_db->indices_local_to_send.", ierr); } l7_id_db->indices_to_send_len = count_total; } /* * Send (global) indices needed from each sending process. */ offset = 0; for (i=0; i<l7_id_db->num_recvs; i++){ #if defined _L7_DEBUG printf("[pe %d] Sending %d indices to pe %d. \n", penum, l7_id_db->recv_counts[i], l7_id_db->recv_from[i] ); for (k=offset; k<offset+l7_id_db->recv_counts[i]; k++){ printf(" index[%d] = %d \n", k, l7_id_db->indices_needed[k] ); } #endif ierr = MPI_Isend(&l7_id_db->indices_needed[offset], l7_id_db->recv_counts[i], MPI_INT, l7_id_db->recv_from[i], L7_SETUP_INDICES_NEEDED_TAG, MPI_COMM_WORLD, &mpi_request[num_outstanding_requests++] ); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Isend ( indices_needed[i] )", ierr); offset+=l7_id_db->recv_counts[i]; } /* * Receive (global) indices needed by the pes to which this pe sends. * Note that these receives are from expected sources. */ offset = 0; for (i=0; i<l7_id_db->num_sends; i++){ ierr = MPI_Irecv(&l7_id_db->indices_global_to_send[offset], l7_id_db->send_counts[i], MPI_INT, l7_id_db->send_to[i], L7_SETUP_INDICES_NEEDED_TAG, MPI_COMM_WORLD, &mpi_request[num_outstanding_requests++] ); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Irecv ( indices_global_to_send )", ierr); offset += l7_id_db->send_counts[i]; } /* * Complete indices communication. */ if (num_outstanding_requests > 0){ ierr = MPI_Waitall(num_outstanding_requests, mpi_request, mpi_status ); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Waitall ( indices )", ierr); } #if defined _L7_DEBUG ierr = MPI_Barrier(MPI_COMM_WORLD); offset = 0; for (j=0; j<numpes; j++){ if (penum == j){ for (i=0; i<l7_id_db->num_sends; i++){ printf("[pe %d] Recvd %d indices from pe %d. \n", penum, l7_id_db->send_counts[i], l7_id_db->send_to[i] ); for (k=offset; k<offset+l7_id_db->send_counts[i]; k++){ printf(" index[%d] = %d \n",k l7_id_db->indices_global_to_send[k] ); } offset += l7_id_db->send_counts[i]; } } sleep(1); } #endif /* Create array of local indices corresponding to * array of global indices requested. Note the * conversion from 1-based indices to 0-based is * accomplished here. (See note in header). */ offset = 0; for (i=0; i<l7_id_db->num_sends; i++){ int counts = l7_id_db->send_counts[i]; // for vectorization int adj = (int)(my_start_index) - base_adj; // for vectorization #ifdef _OPENMP #pragma omp parallel for #endif for (j=0; j<counts; j++){ l7_id_db->indices_local_to_send[offset+j] = l7_id_db->indices_global_to_send[offset+j] - adj; } offset += counts; } #if defined _L7_DEBUG ierr = MPI_Barrier(MPI_COMM_WORLD); for (i=0; i<numpes; i++){ if (penum == i){ for (j=0; j<l7_id_db->num_sends; j++){ printf("[pe %d] send %d indices to pe %d \n", penum, l7_id_db->send_counts[j], l7_id_db->send_to[] ); ierr = MPI_Barrier(MPI_COMM_WORLD); } } } flush(stdout); ierr = MPI_Barrier(MPI_COMM_WORLD); L7_ASSERT(ierr == MPI_SUCCESS, "MPI_Barrier failure", ierr); for (i=0; i<numpes; i++){ if (penum == i){ printf("----------------------------------------------------\n") for (j=0; j<l7_id_db->num_sends; j++){ printf("[pe %d] Send (index %d) to pe %d. \n",penum, l7_id_db->indices_global_to_send[j], l7_id_db->send_to[j] ); } for (j=0; j<l7_id_db->num_recvs; j++){ printf("[pe %d] Recving (index %d) from pe %d. \n",penum, l7_id_db->indices_needed[j], l7_id_db->recv_from[j] ); } printf("----------------------------------------------------\n") fflush(stdout); } sleep(2); } #endif /* _L7_DEBUG */ /* * Ensure buffer available for data to be sent. */ send_buffer_bytes_needed = 0; num_sends = l7_id_db->num_sends; max_sizeof_type = sizeof(double); for (i=0; i<num_sends; i++) send_buffer_bytes_needed += l7_id_db->send_counts[i] * max_sizeof_type; if (send_buffer_bytes_needed > l7.sizeof_send_buffer ){ if (l7.send_buffer) free(l7.send_buffer); l7.send_buffer = (char *)calloc((unsigned long long)send_buffer_bytes_needed, sizeof (char) ); if (l7.send_buffer == NULL){ ierr = -1; L7_ASSERT(l7.send_buffer != NULL, "No memory for send buffer", ierr); } l7.sizeof_send_buffer = send_buffer_bytes_needed; } /* * Message tag management */ l7_id_db->this_tag_update = L7_UPDATE_TAGS_MIN; /* * Database is setup for this l7_id -- return. */ #endif /* HAVE_MPI */ ierr = L7_OK; return(ierr); } /* End L7_Setup */ void L7_SETUP( const int *my_start_index, const int *num_indices_owned, int *indices_needed, const int *num_indices_needed, int *l7_id ) { L7_Setup(0, *my_start_index, *num_indices_owned, indices_needed, *num_indices_needed, l7_id); }
CGOpenMPRuntime.h
//===----- CGOpenMPRuntime.h - Interface to OpenMP Runtimes -----*- 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 provides a class for OpenMP runtime code generation. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #define LLVM_CLANG_LIB_CODEGEN_CGOPENMPRUNTIME_H #include "CGValue.h" #include "clang/AST/DeclOpenMP.h" #include "clang/AST/GlobalDecl.h" #include "clang/AST/Type.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/StringMap.h" #include "llvm/ADT/StringSet.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/IR/Function.h" #include "llvm/IR/ValueHandle.h" #include "llvm/Support/AtomicOrdering.h" namespace llvm { class ArrayType; class Constant; class FunctionType; class GlobalVariable; class StructType; class Type; class Value; } // namespace llvm namespace clang { class Expr; class OMPDependClause; class OMPExecutableDirective; class OMPLoopDirective; class VarDecl; class OMPDeclareReductionDecl; class IdentifierInfo; namespace CodeGen { class Address; class CodeGenFunction; class CodeGenModule; /// A basic class for pre|post-action for advanced codegen sequence for OpenMP /// region. class PrePostActionTy { public: explicit PrePostActionTy() {} virtual void Enter(CodeGenFunction &CGF) {} virtual void Exit(CodeGenFunction &CGF) {} virtual ~PrePostActionTy() {} }; /// Class provides a way to call simple version of codegen for OpenMP region, or /// an advanced with possible pre|post-actions in codegen. class RegionCodeGenTy final { intptr_t CodeGen; typedef void (*CodeGenTy)(intptr_t, CodeGenFunction &, PrePostActionTy &); CodeGenTy Callback; mutable PrePostActionTy *PrePostAction; RegionCodeGenTy() = delete; RegionCodeGenTy &operator=(const RegionCodeGenTy &) = delete; template <typename Callable> static void CallbackFn(intptr_t CodeGen, CodeGenFunction &CGF, PrePostActionTy &Action) { return (*reinterpret_cast<Callable *>(CodeGen))(CGF, Action); } public: template <typename Callable> RegionCodeGenTy( Callable &&CodeGen, std::enable_if_t<!std::is_same<std::remove_reference_t<Callable>, RegionCodeGenTy>::value> * = nullptr) : CodeGen(reinterpret_cast<intptr_t>(&CodeGen)), Callback(CallbackFn<std::remove_reference_t<Callable>>), PrePostAction(nullptr) {} void setAction(PrePostActionTy &Action) const { PrePostAction = &Action; } void operator()(CodeGenFunction &CGF) const; }; struct OMPTaskDataTy final { SmallVector<const Expr *, 4> PrivateVars; SmallVector<const Expr *, 4> PrivateCopies; SmallVector<const Expr *, 4> FirstprivateVars; SmallVector<const Expr *, 4> FirstprivateCopies; SmallVector<const Expr *, 4> FirstprivateInits; SmallVector<const Expr *, 4> LastprivateVars; SmallVector<const Expr *, 4> LastprivateCopies; SmallVector<const Expr *, 4> ReductionVars; SmallVector<const Expr *, 4> ReductionOrigs; SmallVector<const Expr *, 4> ReductionCopies; SmallVector<const Expr *, 4> ReductionOps; struct DependData { OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; const Expr *IteratorExpr = nullptr; SmallVector<const Expr *, 4> DepExprs; explicit DependData() = default; DependData(OpenMPDependClauseKind DepKind, const Expr *IteratorExpr) : DepKind(DepKind), IteratorExpr(IteratorExpr) {} }; SmallVector<DependData, 4> Dependences; llvm::PointerIntPair<llvm::Value *, 1, bool> Final; llvm::PointerIntPair<llvm::Value *, 1, bool> Schedule; llvm::PointerIntPair<llvm::Value *, 1, bool> Priority; llvm::Value *Reductions = nullptr; unsigned NumberOfParts = 0; bool Tied = true; bool Nogroup = false; bool IsReductionWithTaskMod = false; bool IsWorksharingReduction = false; }; /// Class intended to support codegen of all kind of the reduction clauses. class ReductionCodeGen { private: /// Data required for codegen of reduction clauses. struct ReductionData { /// Reference to the item shared between tasks to reduce into. const Expr *Shared = nullptr; /// Reference to the original item. const Expr *Ref = nullptr; /// Helper expression for generation of private copy. const Expr *Private = nullptr; /// Helper expression for generation reduction operation. const Expr *ReductionOp = nullptr; ReductionData(const Expr *Shared, const Expr *Ref, const Expr *Private, const Expr *ReductionOp) : Shared(Shared), Ref(Ref), Private(Private), ReductionOp(ReductionOp) { } }; /// List of reduction-based clauses. SmallVector<ReductionData, 4> ClausesData; /// List of addresses of shared variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> SharedAddresses; /// List of addresses of original variables/expressions. SmallVector<std::pair<LValue, LValue>, 4> OrigAddresses; /// Sizes of the reduction items in chars. SmallVector<std::pair<llvm::Value *, llvm::Value *>, 4> Sizes; /// Base declarations for the reduction items. SmallVector<const VarDecl *, 4> BaseDecls; /// Emits lvalue for shared expression. LValue emitSharedLValue(CodeGenFunction &CGF, const Expr *E); /// Emits upper bound for shared expression (if array section). LValue emitSharedLValueUB(CodeGenFunction &CGF, const Expr *E); /// Performs aggregate initialization. /// \param N Number of reduction item in the common list. /// \param PrivateAddr Address of the corresponding private item. /// \param SharedLVal Address of the original shared variable. /// \param DRD Declare reduction construct used for reduction item. void emitAggregateInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, const OMPDeclareReductionDecl *DRD); public: ReductionCodeGen(ArrayRef<const Expr *> Shareds, ArrayRef<const Expr *> Origs, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> ReductionOps); /// Emits lvalue for the shared and original reduction item. /// \param N Number of the reduction item. void emitSharedOrigLValue(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. void emitAggregateType(CodeGenFunction &CGF, unsigned N); /// Emits the code for the variable-modified type, if required. /// \param N Number of the reduction item. /// \param Size Size of the type in chars. void emitAggregateType(CodeGenFunction &CGF, unsigned N, llvm::Value *Size); /// Performs initialization of the private copy for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. /// \param DefaultInit Default initialization sequence that should be /// performed if no reduction specific initialization is found. /// \param SharedLVal Address of the original shared variable. void emitInitialization(CodeGenFunction &CGF, unsigned N, Address PrivateAddr, LValue SharedLVal, llvm::function_ref<bool(CodeGenFunction &)> DefaultInit); /// Returns true if the private copy requires cleanups. bool needCleanups(unsigned N); /// Emits cleanup code for the reduction item. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. void emitCleanups(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Adjusts \p PrivatedAddr for using instead of the original variable /// address in normal operations. /// \param N Number of the reduction item. /// \param PrivateAddr Address of the corresponding private item. Address adjustPrivateAddress(CodeGenFunction &CGF, unsigned N, Address PrivateAddr); /// Returns LValue for the reduction item. LValue getSharedLValue(unsigned N) const { return SharedAddresses[N].first; } /// Returns LValue for the original reduction item. LValue getOrigLValue(unsigned N) const { return OrigAddresses[N].first; } /// Returns the size of the reduction item (in chars and total number of /// elements in the item), or nullptr, if the size is a constant. std::pair<llvm::Value *, llvm::Value *> getSizes(unsigned N) const { return Sizes[N]; } /// Returns the base declaration of the reduction item. const VarDecl *getBaseDecl(unsigned N) const { return BaseDecls[N]; } /// Returns the base declaration of the reduction item. const Expr *getRefExpr(unsigned N) const { return ClausesData[N].Ref; } /// Returns true if the initialization of the reduction item uses initializer /// from declare reduction construct. bool usesReductionInitializer(unsigned N) const; }; class CGOpenMPRuntime { public: /// Allows to disable automatic handling of functions used in target regions /// as those marked as `omp declare target`. class DisableAutoDeclareTargetRAII { CodeGenModule &CGM; bool SavedShouldMarkAsGlobal; public: DisableAutoDeclareTargetRAII(CodeGenModule &CGM); ~DisableAutoDeclareTargetRAII(); }; /// Manages list of nontemporal decls for the specified directive. class NontemporalDeclsRAII { CodeGenModule &CGM; const bool NeedToPush; public: NontemporalDeclsRAII(CodeGenModule &CGM, const OMPLoopDirective &S); ~NontemporalDeclsRAII(); }; /// Maps the expression for the lastprivate variable to the global copy used /// to store new value because original variables are not mapped in inner /// parallel regions. Only private copies are captured but we need also to /// store private copy in shared address. /// Also, stores the expression for the private loop counter and it /// threaprivate name. struct LastprivateConditionalData { llvm::MapVector<CanonicalDeclPtr<const Decl>, SmallString<16>> DeclToUniqueName; LValue IVLVal; llvm::Function *Fn = nullptr; bool Disabled = false; }; /// Manages list of lastprivate conditional decls for the specified directive. class LastprivateConditionalRAII { enum class ActionToDo { DoNotPush, PushAsLastprivateConditional, DisableLastprivateConditional, }; CodeGenModule &CGM; ActionToDo Action = ActionToDo::DoNotPush; /// Check and try to disable analysis of inner regions for changes in /// lastprivate conditional. void tryToDisableInnerAnalysis(const OMPExecutableDirective &S, llvm::DenseSet<CanonicalDeclPtr<const Decl>> &NeedToAddForLPCsAsDisabled) const; LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S); public: explicit LastprivateConditionalRAII(CodeGenFunction &CGF, const OMPExecutableDirective &S, LValue IVLVal); static LastprivateConditionalRAII disable(CodeGenFunction &CGF, const OMPExecutableDirective &S); ~LastprivateConditionalRAII(); }; protected: CodeGenModule &CGM; StringRef FirstSeparator, Separator; /// Constructor allowing to redefine the name separator for the variables. explicit CGOpenMPRuntime(CodeGenModule &CGM, StringRef FirstSeparator, StringRef Separator); /// Creates offloading entry for the provided entry ID \a ID, /// address \a Addr, size \a Size, and flags \a Flags. virtual void createOffloadEntry(llvm::Constant *ID, llvm::Constant *Addr, uint64_t Size, int32_t Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Helper to emit outlined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Lambda codegen specific to an accelerator device. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunctionHelper(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emits object of ident_t type with info for source location. /// \param Flags Flags for OpenMP location. /// llvm::Value *emitUpdateLocation(CodeGenFunction &CGF, SourceLocation Loc, unsigned Flags = 0); /// Returns pointer to ident_t type. llvm::Type *getIdentTyPointerTy(); /// Gets thread id value for the current thread. /// llvm::Value *getThreadID(CodeGenFunction &CGF, SourceLocation Loc); /// Get the function name of an outlined region. // The name can be customized depending on the target. // virtual StringRef getOutlinedHelperName() const { return ".omp_outlined."; } /// Emits \p Callee function call with arguments \p Args with location \p Loc. void emitCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee Callee, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits address of the word in a memory where current thread id is /// stored. virtual Address emitThreadIDAddress(CodeGenFunction &CGF, SourceLocation Loc); void setLocThreadIdInsertPt(CodeGenFunction &CGF, bool AtCurrentPoint = false); void clearLocThreadIdInsertPt(CodeGenFunction &CGF); /// Check if the default location must be constant. /// Default is false to support OMPT/OMPD. virtual bool isDefaultLocationConstant() const { return false; } /// Returns additional flags that can be stored in reserved_2 field of the /// default location. virtual unsigned getDefaultLocationReserved2Flags() const { return 0; } /// Returns default flags for the barriers depending on the directive, for /// which this barier is going to be emitted. static unsigned getDefaultFlagsForBarriers(OpenMPDirectiveKind Kind); /// Get the LLVM type for the critical name. llvm::ArrayType *getKmpCriticalNameTy() const {return KmpCriticalNameTy;} /// Returns corresponding lock object for the specified critical region /// name. If the lock object does not exist it is created, otherwise the /// reference to the existing copy is returned. /// \param CriticalName Name of the critical region. /// llvm::Value *getCriticalRegionLock(StringRef CriticalName); private: /// Default const ident_t object used for initialization of all other /// ident_t objects. llvm::Constant *DefaultOpenMPPSource = nullptr; using FlagsTy = std::pair<unsigned, unsigned>; /// Map of flags and corresponding default locations. using OpenMPDefaultLocMapTy = llvm::DenseMap<FlagsTy, llvm::Value *>; OpenMPDefaultLocMapTy OpenMPDefaultLocMap; Address getOrCreateDefaultLocation(unsigned Flags); QualType IdentQTy; llvm::StructType *IdentTy = nullptr; /// Map for SourceLocation and OpenMP runtime library debug locations. typedef llvm::DenseMap<unsigned, llvm::Value *> OpenMPDebugLocMapTy; OpenMPDebugLocMapTy OpenMPDebugLocMap; /// The type for a microtask which gets passed to __kmpc_fork_call(). /// Original representation is: /// typedef void (kmpc_micro)(kmp_int32 global_tid, kmp_int32 bound_tid,...); llvm::FunctionType *Kmpc_MicroTy = nullptr; /// Stores debug location and ThreadID for the function. struct DebugLocThreadIdTy { llvm::Value *DebugLoc; llvm::Value *ThreadID; /// Insert point for the service instructions. llvm::AssertingVH<llvm::Instruction> ServiceInsertPt = nullptr; }; /// Map of local debug location, ThreadId and functions. typedef llvm::DenseMap<llvm::Function *, DebugLocThreadIdTy> OpenMPLocThreadIDMapTy; OpenMPLocThreadIDMapTy OpenMPLocThreadIDMap; /// Map of UDRs and corresponding combiner/initializer. typedef llvm::DenseMap<const OMPDeclareReductionDecl *, std::pair<llvm::Function *, llvm::Function *>> UDRMapTy; UDRMapTy UDRMap; /// Map of functions and locally defined UDRs. typedef llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareReductionDecl *, 4>> FunctionUDRMapTy; FunctionUDRMapTy FunctionUDRMap; /// Map from the user-defined mapper declaration to its corresponding /// functions. llvm::DenseMap<const OMPDeclareMapperDecl *, llvm::Function *> UDMMap; /// Map of functions and their local user-defined mappers. using FunctionUDMMapTy = llvm::DenseMap<llvm::Function *, SmallVector<const OMPDeclareMapperDecl *, 4>>; FunctionUDMMapTy FunctionUDMMap; /// Maps local variables marked as lastprivate conditional to their internal /// types. llvm::DenseMap<llvm::Function *, llvm::DenseMap<CanonicalDeclPtr<const Decl>, std::tuple<QualType, const FieldDecl *, const FieldDecl *, LValue>>> LastprivateConditionalToTypes; /// Type kmp_critical_name, originally defined as typedef kmp_int32 /// kmp_critical_name[8]; llvm::ArrayType *KmpCriticalNameTy; /// An ordered map of auto-generated variables to their unique names. /// It stores variables with the following names: 1) ".gomp_critical_user_" + /// <critical_section_name> + ".var" for "omp critical" directives; 2) /// <mangled_name_for_global_var> + ".cache." for cache for threadprivate /// variables. llvm::StringMap<llvm::AssertingVH<llvm::Constant>, llvm::BumpPtrAllocator> InternalVars; /// Type typedef kmp_int32 (* kmp_routine_entry_t)(kmp_int32, void *); llvm::Type *KmpRoutineEntryPtrTy = nullptr; QualType KmpRoutineEntryPtrQTy; /// Type typedef struct kmp_task { /// void * shareds; /**< pointer to block of pointers to /// shared vars */ /// kmp_routine_entry_t routine; /**< pointer to routine to call for /// executing task */ /// kmp_int32 part_id; /**< part id for the task */ /// kmp_routine_entry_t destructors; /* pointer to function to invoke /// deconstructors of firstprivate C++ objects */ /// } kmp_task_t; QualType KmpTaskTQTy; /// Saved kmp_task_t for task directive. QualType SavedKmpTaskTQTy; /// Saved kmp_task_t for taskloop-based directive. QualType SavedKmpTaskloopTQTy; /// Type typedef struct kmp_depend_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool in:1; /// bool out:1; /// } flags; /// } kmp_depend_info_t; QualType KmpDependInfoTy; /// Type typedef struct kmp_task_affinity_info { /// kmp_intptr_t base_addr; /// size_t len; /// struct { /// bool flag1 : 1; /// bool flag2 : 1; /// kmp_int32 reserved : 30; /// } flags; /// } kmp_task_affinity_info_t; QualType KmpTaskAffinityInfoTy; /// struct kmp_dim { // loop bounds info casted to kmp_int64 /// kmp_int64 lo; // lower /// kmp_int64 up; // upper /// kmp_int64 st; // stride /// }; QualType KmpDimTy; /// Type struct __tgt_offload_entry{ /// void *addr; // Pointer to the offload entry info. /// // (function or global) /// char *name; // Name of the function or global. /// size_t size; // Size of the entry info (0 if it a function). /// int32_t flags; /// int32_t reserved; /// }; QualType TgtOffloadEntryQTy; /// Entity that registers the offloading constants that were emitted so /// far. class OffloadEntriesInfoManagerTy { CodeGenModule &CGM; /// Number of entries registered so far. unsigned OffloadingEntriesNum = 0; public: /// Base class of the entries info. class OffloadEntryInfo { public: /// Kind of a given entry. enum OffloadingEntryInfoKinds : unsigned { /// Entry is a target region. OffloadingEntryInfoTargetRegion = 0, /// Entry is a declare target variable. OffloadingEntryInfoDeviceGlobalVar = 1, /// Invalid entry info. OffloadingEntryInfoInvalid = ~0u }; protected: OffloadEntryInfo() = delete; explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind) : Kind(Kind) {} explicit OffloadEntryInfo(OffloadingEntryInfoKinds Kind, unsigned Order, uint32_t Flags) : Flags(Flags), Order(Order), Kind(Kind) {} ~OffloadEntryInfo() = default; public: bool isValid() const { return Order != ~0u; } unsigned getOrder() const { return Order; } OffloadingEntryInfoKinds getKind() const { return Kind; } uint32_t getFlags() const { return Flags; } void setFlags(uint32_t NewFlags) { Flags = NewFlags; } llvm::Constant *getAddress() const { return cast_or_null<llvm::Constant>(Addr); } void setAddress(llvm::Constant *V) { assert(!Addr.pointsToAliveValue() && "Address has been set before!"); Addr = V; } static bool classof(const OffloadEntryInfo *Info) { return true; } private: /// Address of the entity that has to be mapped for offloading. llvm::WeakTrackingVH Addr; /// Flags associated with the device global. uint32_t Flags = 0u; /// Order this entry was emitted. unsigned Order = ~0u; OffloadingEntryInfoKinds Kind = OffloadingEntryInfoInvalid; }; /// Return true if a there are no entries defined. bool empty() const; /// Return number of entries defined so far. unsigned size() const { return OffloadingEntriesNum; } OffloadEntriesInfoManagerTy(CodeGenModule &CGM) : CGM(CGM) {} // // Target region entries related. // /// Kind of the target registry entry. enum OMPTargetRegionEntryKind : uint32_t { /// Mark the entry as target region. OMPTargetRegionEntryTargetRegion = 0x0, /// Mark the entry as a global constructor. OMPTargetRegionEntryCtor = 0x02, /// Mark the entry as a global destructor. OMPTargetRegionEntryDtor = 0x04, }; /// Target region entries info. class OffloadEntryInfoTargetRegion final : public OffloadEntryInfo { /// Address that can be used as the ID of the entry. llvm::Constant *ID = nullptr; public: OffloadEntryInfoTargetRegion() : OffloadEntryInfo(OffloadingEntryInfoTargetRegion) {} explicit OffloadEntryInfoTargetRegion(unsigned Order, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoTargetRegion, Order, Flags), ID(ID) { setAddress(Addr); } llvm::Constant *getID() const { return ID; } void setID(llvm::Constant *V) { assert(!ID && "ID has been set before!"); ID = V; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoTargetRegion; } }; /// Initialize target region entry. void initializeTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, unsigned Order); /// Register target region entry. void registerTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum, llvm::Constant *Addr, llvm::Constant *ID, OMPTargetRegionEntryKind Flags); /// Return true if a target region entry with the provided information /// exists. bool hasTargetRegionEntryInfo(unsigned DeviceID, unsigned FileID, StringRef ParentName, unsigned LineNum) const; /// brief Applies action \a Action on all registered entries. typedef llvm::function_ref<void(unsigned, unsigned, StringRef, unsigned, const OffloadEntryInfoTargetRegion &)> OffloadTargetRegionEntryInfoActTy; void actOnTargetRegionEntriesInfo( const OffloadTargetRegionEntryInfoActTy &Action); // // Device global variable entries related. // /// Kind of the global variable entry.. enum OMPTargetGlobalVarEntryKind : uint32_t { /// Mark the entry as a to declare target. OMPTargetGlobalVarEntryTo = 0x0, /// Mark the entry as a to declare target link. OMPTargetGlobalVarEntryLink = 0x1, }; /// Device global variable entries info. class OffloadEntryInfoDeviceGlobalVar final : public OffloadEntryInfo { /// Type of the global variable. CharUnits VarSize; llvm::GlobalValue::LinkageTypes Linkage; public: OffloadEntryInfoDeviceGlobalVar() : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar) {} explicit OffloadEntryInfoDeviceGlobalVar(unsigned Order, OMPTargetGlobalVarEntryKind Flags) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags) {} explicit OffloadEntryInfoDeviceGlobalVar( unsigned Order, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage) : OffloadEntryInfo(OffloadingEntryInfoDeviceGlobalVar, Order, Flags), VarSize(VarSize), Linkage(Linkage) { setAddress(Addr); } CharUnits getVarSize() const { return VarSize; } void setVarSize(CharUnits Size) { VarSize = Size; } llvm::GlobalValue::LinkageTypes getLinkage() const { return Linkage; } void setLinkage(llvm::GlobalValue::LinkageTypes LT) { Linkage = LT; } static bool classof(const OffloadEntryInfo *Info) { return Info->getKind() == OffloadingEntryInfoDeviceGlobalVar; } }; /// Initialize device global variable entry. void initializeDeviceGlobalVarEntryInfo(StringRef Name, OMPTargetGlobalVarEntryKind Flags, unsigned Order); /// Register device global variable entry. void registerDeviceGlobalVarEntryInfo(StringRef VarName, llvm::Constant *Addr, CharUnits VarSize, OMPTargetGlobalVarEntryKind Flags, llvm::GlobalValue::LinkageTypes Linkage); /// Checks if the variable with the given name has been registered already. bool hasDeviceGlobalVarEntryInfo(StringRef VarName) const { return OffloadEntriesDeviceGlobalVar.count(VarName) > 0; } /// Applies action \a Action on all registered entries. typedef llvm::function_ref<void(StringRef, const OffloadEntryInfoDeviceGlobalVar &)> OffloadDeviceGlobalVarEntryInfoActTy; void actOnDeviceGlobalVarEntriesInfo( const OffloadDeviceGlobalVarEntryInfoActTy &Action); private: // Storage for target region entries kind. The storage is to be indexed by // file ID, device ID, parent function name and line number. typedef llvm::DenseMap<unsigned, OffloadEntryInfoTargetRegion> OffloadEntriesTargetRegionPerLine; typedef llvm::StringMap<OffloadEntriesTargetRegionPerLine> OffloadEntriesTargetRegionPerParentName; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerParentName> OffloadEntriesTargetRegionPerFile; typedef llvm::DenseMap<unsigned, OffloadEntriesTargetRegionPerFile> OffloadEntriesTargetRegionPerDevice; typedef OffloadEntriesTargetRegionPerDevice OffloadEntriesTargetRegionTy; OffloadEntriesTargetRegionTy OffloadEntriesTargetRegion; /// Storage for device global variable entries kind. The storage is to be /// indexed by mangled name. typedef llvm::StringMap<OffloadEntryInfoDeviceGlobalVar> OffloadEntriesDeviceGlobalVarTy; OffloadEntriesDeviceGlobalVarTy OffloadEntriesDeviceGlobalVar; }; OffloadEntriesInfoManagerTy OffloadEntriesInfoManager; bool ShouldMarkAsGlobal = true; /// List of the emitted declarations. llvm::DenseSet<CanonicalDeclPtr<const Decl>> AlreadyEmittedTargetDecls; /// List of the global variables with their addresses that should not be /// emitted for the target. llvm::StringMap<llvm::WeakTrackingVH> EmittedNonTargetVariables; /// List of variables that can become declare target implicitly and, thus, /// must be emitted. llvm::SmallDenseSet<const VarDecl *> DeferredGlobalVariables; using NontemporalDeclsSet = llvm::SmallDenseSet<CanonicalDeclPtr<const Decl>>; /// Stack for list of declarations in current context marked as nontemporal. /// The set is the union of all current stack elements. llvm::SmallVector<NontemporalDeclsSet, 4> NontemporalDeclsStack; /// Stack for list of addresses of declarations in current context marked as /// lastprivate conditional. The set is the union of all current stack /// elements. llvm::SmallVector<LastprivateConditionalData, 4> LastprivateConditionalStack; /// Flag for keeping track of weather a requires unified_shared_memory /// directive is present. bool HasRequiresUnifiedSharedMemory = false; /// Atomic ordering from the omp requires directive. llvm::AtomicOrdering RequiresAtomicOrdering = llvm::AtomicOrdering::Monotonic; /// Flag for keeping track of weather a target region has been emitted. bool HasEmittedTargetRegion = false; /// Flag for keeping track of weather a device routine has been emitted. /// Device routines are specific to the bool HasEmittedDeclareTargetRegion = false; /// Loads all the offload entries information from the host IR /// metadata. void loadOffloadInfoMetadata(); /// Returns __tgt_offload_entry type. QualType getTgtOffloadEntryQTy(); /// Start scanning from statement \a S and and emit all target regions /// found along the way. /// \param S Starting statement. /// \param ParentName Name of the function declaration that is being scanned. void scanForTargetRegionsFunctions(const Stmt *S, StringRef ParentName); /// Build type kmp_routine_entry_t (if not built yet). void emitKmpRoutineEntryT(QualType KmpInt32Ty); /// Returns pointer to kmpc_micro type. llvm::Type *getKmpc_MicroPointerTy(); /// Returns __kmpc_for_static_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createForStaticInitFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_init_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchInitFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_next_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchNextFunction(unsigned IVSize, bool IVSigned); /// Returns __kmpc_dispatch_fini_* runtime function for the specified /// size \a IVSize and sign \a IVSigned. llvm::FunctionCallee createDispatchFiniFunction(unsigned IVSize, bool IVSigned); /// If the specified mangled name is not in the module, create and /// return threadprivate cache object. This object is a pointer's worth of /// storage that's reserved for use by the OpenMP runtime. /// \param VD Threadprivate variable. /// \return Cache variable for the specified threadprivate. llvm::Constant *getOrCreateThreadPrivateCache(const VarDecl *VD); /// Gets (if variable with the given name already exist) or creates /// internal global variable with the specified Name. The created variable has /// linkage CommonLinkage by default and is initialized by null value. /// \param Ty Type of the global variable. If it is exist already the type /// must be the same. /// \param Name Name of the variable. llvm::Constant *getOrCreateInternalVariable(llvm::Type *Ty, const llvm::Twine &Name, unsigned AddressSpace = 0); /// Set of threadprivate variables with the generated initializer. llvm::StringSet<> ThreadPrivateWithDefinition; /// Set of declare target variables with the generated initializer. llvm::StringSet<> DeclareTargetWithDefinition; /// Emits initialization code for the threadprivate variables. /// \param VDAddr Address of the global variable \a VD. /// \param Ctor Pointer to a global init function for \a VD. /// \param CopyCtor Pointer to a global copy function for \a VD. /// \param Dtor Pointer to a global destructor function for \a VD. /// \param Loc Location of threadprivate declaration. void emitThreadPrivateVarInit(CodeGenFunction &CGF, Address VDAddr, llvm::Value *Ctor, llvm::Value *CopyCtor, llvm::Value *Dtor, SourceLocation Loc); /// Emit the array initialization or deletion portion for user-defined mapper /// code generation. void emitUDMapperArrayInitOrDel(CodeGenFunction &MapperCGF, llvm::Value *Handle, llvm::Value *BasePtr, llvm::Value *Ptr, llvm::Value *Size, llvm::Value *MapType, CharUnits ElementSize, llvm::BasicBlock *ExitBB, bool IsInit); struct TaskResultTy { llvm::Value *NewTask = nullptr; llvm::Function *TaskEntry = nullptr; llvm::Value *NewTaskNewTaskTTy = nullptr; LValue TDBase; const RecordDecl *KmpTaskTQTyRD = nullptr; llvm::Value *TaskDupFn = nullptr; }; /// Emit task region for the task directive. The task region is emitted in /// several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. TaskResultTy emitTaskInit(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const OMPTaskDataTy &Data); /// Returns default address space for the constant firstprivates, 0 by /// default. virtual unsigned getDefaultFirstprivateAddressSpace() const { return 0; } /// Emit code that pushes the trip count of loops associated with constructs /// 'target teams distribute' and 'teams distribute parallel for'. /// \param SizeEmitter Emits the int64 value for the number of iterations of /// the associated loop. void emitTargetNumIterationsCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Value *DeviceID, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit update for lastprivate conditional data. void emitLastprivateConditionalUpdate(CodeGenFunction &CGF, LValue IVLVal, StringRef UniqueDeclName, LValue LVal, SourceLocation Loc); /// Returns the number of the elements and the address of the depobj /// dependency array. /// \return Number of elements in depobj array and the pointer to the array of /// dependencies. std::pair<llvm::Value *, LValue> getDepobjElements(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); public: explicit CGOpenMPRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM, ".", ".") {} virtual ~CGOpenMPRuntime() {} virtual void clear(); /// Emits code for OpenMP 'if' clause using specified \a CodeGen /// function. Here is the logic: /// if (Cond) { /// ThenGen(); /// } else { /// ElseGen(); /// } void emitIfClause(CodeGenFunction &CGF, const Expr *Cond, const RegionCodeGenTy &ThenGen, const RegionCodeGenTy &ElseGen); /// Checks if the \p Body is the \a CompoundStmt and returns its child /// statement iff there is only one that is not evaluatable at the compile /// time. static const Stmt *getSingleCompoundChild(ASTContext &Ctx, const Stmt *Body); /// Get the platform-specific name separator. std::string getName(ArrayRef<StringRef> Parts) const; /// Emit code for the specified user defined reduction construct. virtual void emitUserDefinedReduction(CodeGenFunction *CGF, const OMPDeclareReductionDecl *D); /// Get combiner/initializer for the specified user-defined reduction, if any. virtual std::pair<llvm::Function *, llvm::Function *> getUserDefinedReduction(const OMPDeclareReductionDecl *D); /// Emit the function for the user defined mapper construct. void emitUserDefinedMapper(const OMPDeclareMapperDecl *D, CodeGenFunction *CGF = nullptr); /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitParallelOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. virtual llvm::Function *emitTeamsOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen); /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// virtual llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts); /// Cleans up references to the objects in finished function. /// virtual void functionFinished(CodeGenFunction &CGF); /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// virtual void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond); /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). virtual void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr); /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. virtual void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc); /// Emits code for a taskyield directive. virtual void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc); /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. virtual void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc); /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. virtual void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps); /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. virtual void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads); /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// virtual void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false); /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// This kind of distribute directive is emitted without outer loop. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticNonchunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static chunked. /// \param ScheduleKind Schedule kind specified in the 'schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is static non-chunked. /// \param ScheduleKind Schedule kind specified in the 'dist_schedule' clause. /// \param Chunked True if chunk is specified in the clause. /// virtual bool isStaticChunked(OpenMPDistScheduleClauseKind ScheduleKind, bool Chunked) const; /// Check if the specified \a ScheduleKind is dynamic. /// This kind of worksharing directive is emitted without outer loop. /// \param ScheduleKind Schedule Kind specified in the 'schedule' clause. /// virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const; /// struct with the values to be passed to the dispatch runtime function struct DispatchRTInput { /// Loop lower bound llvm::Value *LB = nullptr; /// Loop upper bound llvm::Value *UB = nullptr; /// Chunk size specified using 'schedule' clause (nullptr if chunk /// was not specified) llvm::Value *Chunk = nullptr; DispatchRTInput() = default; DispatchRTInput(llvm::Value *LB, llvm::Value *UB, llvm::Value *Chunk) : LB(LB), UB(UB), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// virtual void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues); /// Struct with the values to be passed to the static runtime function struct StaticRTInput { /// Size of the iteration variable in bits. unsigned IVSize = 0; /// Sign of the iteration variable. bool IVSigned = false; /// true if loop is ordered, false otherwise. bool Ordered = false; /// Address of the output variable in which the flag of the last iteration /// is returned. Address IL = Address::invalid(); /// Address of the output variable in which the lower iteration number is /// returned. Address LB = Address::invalid(); /// Address of the output variable in which the upper iteration number is /// returned. Address UB = Address::invalid(); /// Address of the output variable in which the stride value is returned /// necessary to generated the static_chunked scheduled loop. Address ST = Address::invalid(); /// Value of the chunk for the static_chunked scheduled loop. For the /// default (nullptr) value, the chunk 1 will be used. llvm::Value *Chunk = nullptr; StaticRTInput(unsigned IVSize, bool IVSigned, bool Ordered, Address IL, Address LB, Address UB, Address ST, llvm::Value *Chunk = nullptr) : IVSize(IVSize), IVSigned(IVSigned), Ordered(Ordered), IL(IL), LB(LB), UB(UB), ST(ST), Chunk(Chunk) {} }; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values); /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// virtual void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values); /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// virtual void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned); /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// virtual void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind); /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. virtual llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST); /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. virtual void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc); /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. virtual void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc); /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. virtual Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc); /// Returns the address of the variable marked as declare target with link /// clause OR as declare target with to clause and unified memory. virtual Address getAddrOfDeclareTargetVar(const VarDecl *VD); /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. virtual llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr); /// Emit a code for initialization of declare target variable. /// \param VD Declare target variable. /// \param Addr Address of the global variable \a VD. /// \param PerformInit true if initialization expression is not constant. virtual bool emitDeclareTargetVarDefinition(const VarDecl *VD, llvm::GlobalVariable *Addr, bool PerformInit); /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. virtual Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name); /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. virtual void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO); /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. virtual void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data); /// Emit code for the directive that does not require outlining. /// /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param HasCancel true if region has inner cancel directive, false /// otherwise. virtual void emitInlinedDirective(CodeGenFunction &CGF, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool HasCancel = false); /// Emits reduction function. /// \param ArgsType Array type containing pointers to reduction variables. /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. llvm::Function *emitReductionFunction(SourceLocation Loc, llvm::Type *ArgsType, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps); /// Emits single reduction combiner void emitSingleReductionCombiner(CodeGenFunction &CGF, const Expr *ReductionOp, const Expr *PrivateRef, const DeclRefExpr *LHS, const DeclRefExpr *RHS); struct ReductionOptionsTy { bool WithNowait; bool SimpleReduction; OpenMPDirectiveKind ReductionKind; }; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. virtual void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options); /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. virtual llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data); /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode virtual void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction); /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. virtual void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N); /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. virtual Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal); /// Emit code for 'taskwait' directive. virtual void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc); /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// virtual void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion); /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// virtual void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion); /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. virtual void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen); /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. /// \param SizeEmitter Callback to emit number of iterations for loop-based /// directives. virtual void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter); /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. virtual bool emitTargetFunctions(GlobalDecl GD); /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. virtual bool emitTargetGlobalVariable(GlobalDecl GD); /// Checks if the provided global decl \a GD is a declare target variable and /// registers it when emitting code for the host. virtual void registerTargetGlobalVariable(const VarDecl *VD, llvm::Constant *Addr); /// Registers provided target firstprivate variable as global on the /// target. llvm::Constant *registerTargetFirstprivateCopy(CodeGenFunction &CGF, const VarDecl *VD); /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. virtual bool emitTargetGlobal(GlobalDecl GD); /// Creates and returns a registration function for when at least one /// requires directives was used in the current module. llvm::Function *emitRequiresDirectiveRegFun(); /// Creates all the offload entries in the current compilation unit /// along with the associated metadata. void createOffloadEntriesAndInfoMetadata(); /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// virtual void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars); /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. virtual void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc); /// Struct that keeps all the relevant information that should be kept /// throughout a 'target data' region. class TargetDataInfo { /// Set to true if device pointer information have to be obtained. bool RequiresDevicePointerInfo = false; public: /// The array of base pointer passed to the runtime library. llvm::Value *BasePointersArray = nullptr; /// The array of section pointers passed to the runtime library. llvm::Value *PointersArray = nullptr; /// The array of sizes passed to the runtime library. llvm::Value *SizesArray = nullptr; /// The array of map types passed to the runtime library. llvm::Value *MapTypesArray = nullptr; /// The total number of pointers passed to the runtime library. unsigned NumberOfPtrs = 0u; /// Map between the a declaration of a capture and the corresponding base /// pointer address where the runtime returns the device pointers. llvm::DenseMap<const ValueDecl *, Address> CaptureDeviceAddrMap; explicit TargetDataInfo() {} explicit TargetDataInfo(bool RequiresDevicePointerInfo) : RequiresDevicePointerInfo(RequiresDevicePointerInfo) {} /// Clear information about the data arrays. void clearArrayInfo() { BasePointersArray = nullptr; PointersArray = nullptr; SizesArray = nullptr; MapTypesArray = nullptr; NumberOfPtrs = 0u; } /// Return true if the current target data information has valid arrays. bool isValid() { return BasePointersArray && PointersArray && SizesArray && MapTypesArray && NumberOfPtrs; } bool requiresDevicePointerInfo() { return RequiresDevicePointerInfo; } }; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. virtual void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info); /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. virtual void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device); /// Marks function \a Fn with properly mangled versions of vector functions. /// \param FD Function marked as 'declare simd'. /// \param Fn LLVM function that must be marked with 'declare simd' /// attributes. virtual void emitDeclareSimdFunction(const FunctionDecl *FD, llvm::Function *Fn); /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. virtual void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations); /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. virtual void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C); /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. virtual const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const { return NativeParam; } /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. virtual Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const; /// Choose default schedule type and chunk value for the /// dist_schedule clause. virtual void getDefaultDistScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPDistScheduleClauseKind &ScheduleKind, llvm::Value *&Chunk) const {} /// Choose default schedule type and chunk value for the /// schedule clause. virtual void getDefaultScheduleAndChunk(CodeGenFunction &CGF, const OMPLoopDirective &S, OpenMPScheduleClauseKind &ScheduleKind, const Expr *&ChunkExpr) const; /// Emits call of the outlined function with the provided arguments, /// translating these arguments to correct target-specific arguments. virtual void emitOutlinedFunctionCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::FunctionCallee OutlinedFn, ArrayRef<llvm::Value *> Args = llvm::None) const; /// Emits OpenMP-specific function prolog. /// Required for device constructs. virtual void emitFunctionProlog(CodeGenFunction &CGF, const Decl *D); /// Gets the OpenMP-specific address of the local variable. virtual Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD); /// Marks the declaration as already emitted for the device code and returns /// true, if it was marked already, and false, otherwise. bool markAsGlobalTarget(GlobalDecl GD); /// Emit deferred declare target variables marked for deferred emission. void emitDeferredTargetDecls() const; /// Adjust some parameters for the target-based directives, like addresses of /// the variables captured by reference in lambdas. virtual void adjustTargetSpecificDataForLambdas(CodeGenFunction &CGF, const OMPExecutableDirective &D) const; /// Perform check on requires decl to ensure that target architecture /// supports unified addressing virtual void processRequiresDirective(const OMPRequiresDecl *D); /// Gets default memory ordering as specified in requires directive. llvm::AtomicOrdering getDefaultMemoryOrdering() const; /// Checks if the variable has associated OMPAllocateDeclAttr attribute with /// the predefined allocator and translates it into the corresponding address /// space. virtual bool hasAllocateAttributeForGlobalVar(const VarDecl *VD, LangAS &AS); /// Return whether the unified_shared_memory has been specified. bool hasRequiresUnifiedSharedMemory() const; /// Checks if the \p VD variable is marked as nontemporal declaration in /// current context. bool isNontemporalDecl(const ValueDecl *VD) const; /// Create specialized alloca to handle lastprivate conditionals. Address emitLastprivateConditionalInit(CodeGenFunction &CGF, const VarDecl *VD); /// Checks if the provided \p LVal is lastprivate conditional and emits the /// code to update the value of the original variable. /// \code /// lastprivate(conditional: a) /// ... /// <type> a; /// lp_a = ...; /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// \endcode virtual void checkAndEmitLastprivateConditional(CodeGenFunction &CGF, const Expr *LHS); /// Checks if the lastprivate conditional was updated in inner region and /// writes the value. /// \code /// lastprivate(conditional: a) /// ... /// <type> a;bool Fired = false; /// #pragma omp ... shared(a) /// { /// lp_a = ...; /// Fired = true; /// } /// if (Fired) { /// #pragma omp critical(a) /// if (last_iv_a <= iv) { /// last_iv_a = iv; /// global_a = lp_a; /// } /// Fired = false; /// } /// \endcode virtual void checkAndEmitSharedLastprivateConditional( CodeGenFunction &CGF, const OMPExecutableDirective &D, const llvm::DenseSet<CanonicalDeclPtr<const VarDecl>> &IgnoredDecls); /// Gets the address of the global copy used for lastprivate conditional /// update, if any. /// \param PrivLVal LValue for the private copy. /// \param VD Original lastprivate declaration. virtual void emitLastprivateConditionalFinalUpdate(CodeGenFunction &CGF, LValue PrivLVal, const VarDecl *VD, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs). /// \returns Pointer to the first element of the array casted to VoidPtr type. std::pair<llvm::Value *, Address> emitDependClause(CodeGenFunction &CGF, ArrayRef<OMPTaskDataTy::DependData> Dependencies, SourceLocation Loc); /// Emits list of dependecies based on the provided data (array of /// dependence/expression pairs) for depobj construct. In this case, the /// variable is allocated in dynamically. \returns Pointer to the first /// element of the array casted to VoidPtr type. Address emitDepobjDependClause(CodeGenFunction &CGF, const OMPTaskDataTy::DependData &Dependencies, SourceLocation Loc); /// Emits the code to destroy the dependency object provided in depobj /// directive. void emitDestroyClause(CodeGenFunction &CGF, LValue DepobjLVal, SourceLocation Loc); /// Updates the dependency kind in the specified depobj object. /// \param DepobjLVal LValue for the main depobj object. /// \param NewDepKind New dependency kind. void emitUpdateClause(CodeGenFunction &CGF, LValue DepobjLVal, OpenMPDependClauseKind NewDepKind, SourceLocation Loc); /// Initializes user defined allocators specified in the uses_allocators /// clauses. void emitUsesAllocatorsInit(CodeGenFunction &CGF, const Expr *Allocator, const Expr *AllocatorTraits); /// Destroys user defined allocators specified in the uses_allocators clause. void emitUsesAllocatorsFini(CodeGenFunction &CGF, const Expr *Allocator); }; /// Class supports emissionof SIMD-only code. class CGOpenMPSIMDRuntime final : public CGOpenMPRuntime { public: explicit CGOpenMPSIMDRuntime(CodeGenModule &CGM) : CGOpenMPRuntime(CGM) {} ~CGOpenMPSIMDRuntime() override {} /// Emits outlined function for the specified OpenMP parallel directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitParallelOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the specified OpenMP teams directive /// \a D. This outlined function has type void(*)(kmp_int32 *ThreadID, /// kmp_int32 BoundID, struct context_vars*). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. llvm::Function * emitTeamsOutlinedFunction(const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen) override; /// Emits outlined function for the OpenMP task directive \a D. This /// outlined function has type void(*)(kmp_int32 ThreadID, struct task_t* /// TaskT). /// \param D OpenMP directive. /// \param ThreadIDVar Variable for thread id in the current OpenMP region. /// \param PartIDVar Variable for partition id in the current OpenMP untied /// task region. /// \param TaskTVar Variable for task_t argument. /// \param InnermostKind Kind of innermost directive (for simple directives it /// is a directive itself, for combined - its innermost directive). /// \param CodeGen Code generation sequence for the \a D directive. /// \param Tied true if task is generated for tied task, false otherwise. /// \param NumberOfParts Number of parts in untied task. Ignored for tied /// tasks. /// llvm::Function *emitTaskOutlinedFunction( const OMPExecutableDirective &D, const VarDecl *ThreadIDVar, const VarDecl *PartIDVar, const VarDecl *TaskTVar, OpenMPDirectiveKind InnermostKind, const RegionCodeGenTy &CodeGen, bool Tied, unsigned &NumberOfParts) override; /// Emits code for parallel or serial call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run in parallel threads. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// void emitParallelCall(CodeGenFunction &CGF, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars, const Expr *IfCond) override; /// Emits a critical region. /// \param CriticalName Name of the critical region. /// \param CriticalOpGen Generator for the statement associated with the given /// critical region. /// \param Hint Value of the 'hint' clause (optional). void emitCriticalRegion(CodeGenFunction &CGF, StringRef CriticalName, const RegionCodeGenTy &CriticalOpGen, SourceLocation Loc, const Expr *Hint = nullptr) override; /// Emits a master region. /// \param MasterOpGen Generator for the statement associated with the given /// master region. void emitMasterRegion(CodeGenFunction &CGF, const RegionCodeGenTy &MasterOpGen, SourceLocation Loc) override; /// Emits code for a taskyield directive. void emitTaskyieldCall(CodeGenFunction &CGF, SourceLocation Loc) override; /// Emit a taskgroup region. /// \param TaskgroupOpGen Generator for the statement associated with the /// given taskgroup region. void emitTaskgroupRegion(CodeGenFunction &CGF, const RegionCodeGenTy &TaskgroupOpGen, SourceLocation Loc) override; /// Emits a single region. /// \param SingleOpGen Generator for the statement associated with the given /// single region. void emitSingleRegion(CodeGenFunction &CGF, const RegionCodeGenTy &SingleOpGen, SourceLocation Loc, ArrayRef<const Expr *> CopyprivateVars, ArrayRef<const Expr *> DestExprs, ArrayRef<const Expr *> SrcExprs, ArrayRef<const Expr *> AssignmentOps) override; /// Emit an ordered region. /// \param OrderedOpGen Generator for the statement associated with the given /// ordered region. void emitOrderedRegion(CodeGenFunction &CGF, const RegionCodeGenTy &OrderedOpGen, SourceLocation Loc, bool IsThreads) override; /// Emit an implicit/explicit barrier for OpenMP threads. /// \param Kind Directive for which this implicit barrier call must be /// generated. Must be OMPD_barrier for explicit barrier generation. /// \param EmitChecks true if need to emit checks for cancellation barriers. /// \param ForceSimpleCall true simple barrier call must be emitted, false if /// runtime class decides which one to emit (simple or with cancellation /// checks). /// void emitBarrierCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind Kind, bool EmitChecks = true, bool ForceSimpleCall = false) override; /// This is used for non static scheduled types and when the ordered /// clause is present on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds \a LB and \a UB and stride \a ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param Ordered true if loop is ordered, false otherwise. /// \param DispatchValues struct containing llvm values for lower bound, upper /// bound, and chunk expression. /// For the default (nullptr) value, the chunk 1 will be used. /// void emitForDispatchInit(CodeGenFunction &CGF, SourceLocation Loc, const OpenMPScheduleTy &ScheduleKind, unsigned IVSize, bool IVSigned, bool Ordered, const DispatchRTInput &DispatchValues) override; /// Call the appropriate runtime routine to initialize it before start /// of loop. /// /// This is used only in case of static schedule, when the user did not /// specify a ordered clause on the loop construct. /// Depending on the loop schedule, it is necessary to call some runtime /// routine before start of the OpenMP loop to get the loop upper / lower /// bounds LB and UB and stride ST. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive. /// \param ScheduleKind Schedule kind, specified by the 'schedule' clause. /// \param Values Input arguments for the construct. /// void emitForStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind, const OpenMPScheduleTy &ScheduleKind, const StaticRTInput &Values) override; /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param SchedKind Schedule kind, specified by the 'dist_schedule' clause. /// \param Values Input arguments for the construct. /// void emitDistributeStaticInit(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDistScheduleClauseKind SchedKind, const StaticRTInput &Values) override; /// Call the appropriate runtime routine to notify that we finished /// iteration of the ordered loop with the dynamic scheduling. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// void emitForOrderedIterationEnd(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned) override; /// Call the appropriate runtime routine to notify that we finished /// all the work with current loop. /// /// \param CGF Reference to current CodeGenFunction. /// \param Loc Clang source location. /// \param DKind Kind of the directive for which the static finish is emitted. /// void emitForStaticFinish(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind DKind) override; /// Call __kmpc_dispatch_next( /// ident_t *loc, kmp_int32 tid, kmp_int32 *p_lastiter, /// kmp_int[32|64] *p_lower, kmp_int[32|64] *p_upper, /// kmp_int[32|64] *p_stride); /// \param IVSize Size of the iteration variable in bits. /// \param IVSigned Sign of the iteration variable. /// \param IL Address of the output variable in which the flag of the /// last iteration is returned. /// \param LB Address of the output variable in which the lower iteration /// number is returned. /// \param UB Address of the output variable in which the upper iteration /// number is returned. /// \param ST Address of the output variable in which the stride value is /// returned. llvm::Value *emitForNext(CodeGenFunction &CGF, SourceLocation Loc, unsigned IVSize, bool IVSigned, Address IL, Address LB, Address UB, Address ST) override; /// Emits call to void __kmpc_push_num_threads(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_threads) to generate code for 'num_threads' /// clause. /// \param NumThreads An integer value of threads. void emitNumThreadsClause(CodeGenFunction &CGF, llvm::Value *NumThreads, SourceLocation Loc) override; /// Emit call to void __kmpc_push_proc_bind(ident_t *loc, kmp_int32 /// global_tid, int proc_bind) to generate code for 'proc_bind' clause. void emitProcBindClause(CodeGenFunction &CGF, llvm::omp::ProcBindKind ProcBind, SourceLocation Loc) override; /// Returns address of the threadprivate variable for the current /// thread. /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of the reference to threadprivate var. /// \return Address of the threadprivate variable for the current thread. Address getAddrOfThreadPrivate(CodeGenFunction &CGF, const VarDecl *VD, Address VDAddr, SourceLocation Loc) override; /// Emit a code for initialization of threadprivate variable. It emits /// a call to runtime library which adds initial value to the newly created /// threadprivate variable (if it is not constant) and registers destructor /// for the variable (if any). /// \param VD Threadprivate variable. /// \param VDAddr Address of the global variable \a VD. /// \param Loc Location of threadprivate declaration. /// \param PerformInit true if initialization expression is not constant. llvm::Function * emitThreadPrivateVarDefinition(const VarDecl *VD, Address VDAddr, SourceLocation Loc, bool PerformInit, CodeGenFunction *CGF = nullptr) override; /// Creates artificial threadprivate variable with name \p Name and type \p /// VarType. /// \param VarType Type of the artificial threadprivate variable. /// \param Name Name of the artificial threadprivate variable. Address getAddrOfArtificialThreadPrivate(CodeGenFunction &CGF, QualType VarType, StringRef Name) override; /// Emit flush of the variables specified in 'omp flush' directive. /// \param Vars List of variables to flush. void emitFlush(CodeGenFunction &CGF, ArrayRef<const Expr *> Vars, SourceLocation Loc, llvm::AtomicOrdering AO) override; /// Emit task region for the task directive. The task region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to kmp_int32 __kmpc_omp_task(ident_t *, kmp_int32 gtid, /// kmp_task_t *new_task), where new_task is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPExecutableDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit task region for the taskloop directive. The taskloop region is /// emitted in several steps: /// 1. Emit a call to kmp_task_t *__kmpc_omp_task_alloc(ident_t *, kmp_int32 /// gtid, kmp_int32 flags, size_t sizeof_kmp_task_t, size_t sizeof_shareds, /// kmp_routine_entry_t *task_entry). Here task_entry is a pointer to the /// function: /// kmp_int32 .omp_task_entry.(kmp_int32 gtid, kmp_task_t *tt) { /// TaskFunction(gtid, tt->part_id, tt->shareds); /// return 0; /// } /// 2. Copy a list of shared variables to field shareds of the resulting /// structure kmp_task_t returned by the previous call (if any). /// 3. Copy a pointer to destructions function to field destructions of the /// resulting structure kmp_task_t. /// 4. Emit a call to void __kmpc_taskloop(ident_t *loc, int gtid, kmp_task_t /// *task, int if_val, kmp_uint64 *lb, kmp_uint64 *ub, kmp_int64 st, int /// nogroup, int sched, kmp_uint64 grainsize, void *task_dup ), where new_task /// is a resulting structure from /// previous items. /// \param D Current task directive. /// \param TaskFunction An LLVM function with type void (*)(i32 /*gtid*/, i32 /// /*part_id*/, captured_struct */*__context*/); /// \param SharedsTy A type which contains references the shared variables. /// \param Shareds Context with the list of shared variables from the \p /// TaskFunction. /// \param IfCond Not a nullptr if 'if' clause was specified, nullptr /// otherwise. /// \param Data Additional data for task generation like tiednsee, final /// state, list of privates etc. void emitTaskLoopCall(CodeGenFunction &CGF, SourceLocation Loc, const OMPLoopDirective &D, llvm::Function *TaskFunction, QualType SharedsTy, Address Shareds, const Expr *IfCond, const OMPTaskDataTy &Data) override; /// Emit a code for reduction clause. Next code should be emitted for /// reduction: /// \code /// /// static kmp_critical_name lock = { 0 }; /// /// void reduce_func(void *lhs[<n>], void *rhs[<n>]) { /// ... /// *(Type<i>*)lhs[i] = RedOp<i>(*(Type<i>*)lhs[i], *(Type<i>*)rhs[i]); /// ... /// } /// /// ... /// void *RedList[<n>] = {&<RHSExprs>[0], ..., &<RHSExprs>[<n>-1]}; /// switch (__kmpc_reduce{_nowait}(<loc>, <gtid>, <n>, sizeof(RedList), /// RedList, reduce_func, &<lock>)) { /// case 1: /// ... /// <LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i]); /// ... /// __kmpc_end_reduce{_nowait}(<loc>, <gtid>, &<lock>); /// break; /// case 2: /// ... /// Atomic(<LHSExprs>[i] = RedOp<i>(*<LHSExprs>[i], *<RHSExprs>[i])); /// ... /// break; /// default:; /// } /// \endcode /// /// \param Privates List of private copies for original reduction arguments. /// \param LHSExprs List of LHS in \a ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a ReductionOps reduction operations. /// \param ReductionOps List of reduction operations in form 'LHS binop RHS' /// or 'operator binop(LHS, RHS)'. /// \param Options List of options for reduction codegen: /// WithNowait true if parent directive has also nowait clause, false /// otherwise. /// SimpleReduction Emit reduction operation only. Used for omp simd /// directive on the host. /// ReductionKind The kind of reduction to perform. void emitReduction(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> Privates, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, ArrayRef<const Expr *> ReductionOps, ReductionOptionsTy Options) override; /// Emit a code for initialization of task reduction clause. Next code /// should be emitted for reduction: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_init(gtid, n, red_data); /// \endcode /// For reduction clause with task modifier it emits the next call: /// \code /// /// _taskred_item_t red_data[n]; /// ... /// red_data[i].shar = &shareds[i]; /// red_data[i].orig = &origs[i]; /// red_data[i].size = sizeof(origs[i]); /// red_data[i].f_init = (void*)RedInit<i>; /// red_data[i].f_fini = (void*)RedDest<i>; /// red_data[i].f_comb = (void*)RedOp<i>; /// red_data[i].flags = <Flag_i>; /// ... /// void* tg1 = __kmpc_taskred_modifier_init(loc, gtid, is_worksharing, n, /// red_data); /// \endcode /// \param LHSExprs List of LHS in \a Data.ReductionOps reduction operations. /// \param RHSExprs List of RHS in \a Data.ReductionOps reduction operations. /// \param Data Additional data for task generation like tiedness, final /// state, list of privates, reductions etc. llvm::Value *emitTaskReductionInit(CodeGenFunction &CGF, SourceLocation Loc, ArrayRef<const Expr *> LHSExprs, ArrayRef<const Expr *> RHSExprs, const OMPTaskDataTy &Data) override; /// Emits the following code for reduction clause with task modifier: /// \code /// __kmpc_task_reduction_modifier_fini(loc, gtid, is_worksharing); /// \endcode void emitTaskReductionFini(CodeGenFunction &CGF, SourceLocation Loc, bool IsWorksharingReduction) override; /// Required to resolve existing problems in the runtime. Emits threadprivate /// variables to store the size of the VLAs/array sections for /// initializer/combiner/finalizer functions + emits threadprivate variable to /// store the pointer to the original reduction item for the custom /// initializer defined by declare reduction construct. /// \param RCG Allows to reuse an existing data for the reductions. /// \param N Reduction item for which fixups must be emitted. void emitTaskReductionFixups(CodeGenFunction &CGF, SourceLocation Loc, ReductionCodeGen &RCG, unsigned N) override; /// Get the address of `void *` type of the privatue copy of the reduction /// item specified by the \p SharedLVal. /// \param ReductionsPtr Pointer to the reduction data returned by the /// emitTaskReductionInit function. /// \param SharedLVal Address of the original reduction item. Address getTaskReductionItem(CodeGenFunction &CGF, SourceLocation Loc, llvm::Value *ReductionsPtr, LValue SharedLVal) override; /// Emit code for 'taskwait' directive. void emitTaskwaitCall(CodeGenFunction &CGF, SourceLocation Loc) override; /// Emit code for 'cancellation point' construct. /// \param CancelRegion Region kind for which the cancellation point must be /// emitted. /// void emitCancellationPointCall(CodeGenFunction &CGF, SourceLocation Loc, OpenMPDirectiveKind CancelRegion) override; /// Emit code for 'cancel' construct. /// \param IfCond Condition in the associated 'if' clause, if it was /// specified, nullptr otherwise. /// \param CancelRegion Region kind for which the cancel must be emitted. /// void emitCancelCall(CodeGenFunction &CGF, SourceLocation Loc, const Expr *IfCond, OpenMPDirectiveKind CancelRegion) override; /// Emit outilined function for 'target' directive. /// \param D Directive to emit. /// \param ParentName Name of the function that encloses the target region. /// \param OutlinedFn Outlined function value to be defined by this call. /// \param OutlinedFnID Outlined function ID value to be defined by this call. /// \param IsOffloadEntry True if the outlined function is an offload entry. /// \param CodeGen Code generation sequence for the \a D directive. /// An outlined function may not be an entry if, e.g. the if clause always /// evaluates to false. void emitTargetOutlinedFunction(const OMPExecutableDirective &D, StringRef ParentName, llvm::Function *&OutlinedFn, llvm::Constant *&OutlinedFnID, bool IsOffloadEntry, const RegionCodeGenTy &CodeGen) override; /// Emit the target offloading code associated with \a D. The emitted /// code attempts offloading the execution to the device, an the event of /// a failure it executes the host version outlined in \a OutlinedFn. /// \param D Directive to emit. /// \param OutlinedFn Host version of the code to be offloaded. /// \param OutlinedFnID ID of host version of the code to be offloaded. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used and device modifier. void emitTargetCall( CodeGenFunction &CGF, const OMPExecutableDirective &D, llvm::Function *OutlinedFn, llvm::Value *OutlinedFnID, const Expr *IfCond, llvm::PointerIntPair<const Expr *, 2, OpenMPDeviceClauseModifier> Device, llvm::function_ref<llvm::Value *(CodeGenFunction &CGF, const OMPLoopDirective &D)> SizeEmitter) override; /// Emit the target regions enclosed in \a GD function definition or /// the function itself in case it is a valid device function. Returns true if /// \a GD was dealt with successfully. /// \param GD Function to scan. bool emitTargetFunctions(GlobalDecl GD) override; /// Emit the global variable if it is a valid device global variable. /// Returns true if \a GD was dealt with successfully. /// \param GD Variable declaration to emit. bool emitTargetGlobalVariable(GlobalDecl GD) override; /// Emit the global \a GD if it is meaningful for the target. Returns /// if it was emitted successfully. /// \param GD Global to scan. bool emitTargetGlobal(GlobalDecl GD) override; /// Emits code for teams call of the \a OutlinedFn with /// variables captured in a record which address is stored in \a /// CapturedStruct. /// \param OutlinedFn Outlined function to be run by team masters. Type of /// this function is void(*)(kmp_int32 *, kmp_int32, struct context_vars*). /// \param CapturedVars A pointer to the record with the references to /// variables used in \a OutlinedFn function. /// void emitTeamsCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, SourceLocation Loc, llvm::Function *OutlinedFn, ArrayRef<llvm::Value *> CapturedVars) override; /// Emits call to void __kmpc_push_num_teams(ident_t *loc, kmp_int32 /// global_tid, kmp_int32 num_teams, kmp_int32 thread_limit) to generate code /// for num_teams clause. /// \param NumTeams An integer expression of teams. /// \param ThreadLimit An integer expression of threads. void emitNumTeamsClause(CodeGenFunction &CGF, const Expr *NumTeams, const Expr *ThreadLimit, SourceLocation Loc) override; /// Emit the target data mapping code associated with \a D. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the /// target directive, or null if no device clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. /// \param Info A record used to store information that needs to be preserved /// until the region is closed. void emitTargetDataCalls(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device, const RegionCodeGenTy &CodeGen, TargetDataInfo &Info) override; /// Emit the data mapping/movement code associated with the directive /// \a D that should be of the form 'target [{enter|exit} data | update]'. /// \param D Directive to emit. /// \param IfCond Expression evaluated in if clause associated with the target /// directive, or null if no if clause is used. /// \param Device Expression evaluated in device clause associated with the /// target directive, or null if no device clause is used. void emitTargetDataStandAloneCall(CodeGenFunction &CGF, const OMPExecutableDirective &D, const Expr *IfCond, const Expr *Device) override; /// Emit initialization for doacross loop nesting support. /// \param D Loop-based construct used in doacross nesting construct. void emitDoacrossInit(CodeGenFunction &CGF, const OMPLoopDirective &D, ArrayRef<Expr *> NumIterations) override; /// Emit code for doacross ordered directive with 'depend' clause. /// \param C 'depend' clause with 'sink|source' dependency kind. void emitDoacrossOrdered(CodeGenFunction &CGF, const OMPDependClause *C) override; /// Translates the native parameter of outlined function if this is required /// for target. /// \param FD Field decl from captured record for the parameter. /// \param NativeParam Parameter itself. const VarDecl *translateParameter(const FieldDecl *FD, const VarDecl *NativeParam) const override; /// Gets the address of the native argument basing on the address of the /// target-specific parameter. /// \param NativeParam Parameter itself. /// \param TargetParam Corresponding target-specific parameter. Address getParameterAddress(CodeGenFunction &CGF, const VarDecl *NativeParam, const VarDecl *TargetParam) const override; /// Gets the OpenMP-specific address of the local variable. Address getAddressOfLocalVariable(CodeGenFunction &CGF, const VarDecl *VD) override { return Address::invalid(); } }; } // namespace CodeGen } // namespace clang #endif
p3.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define VECLEN 100000000 double *a, *b, sum; double begin; double time_spent; int main (int argc, char *argv[]) { int i; sum = 0.0; a = aligned_alloc(64, VECLEN * sizeof(double)); b = aligned_alloc(64, VECLEN * sizeof(double)); for (i=0; i < VECLEN; i++) a[i] = b[i] = 1.0 * i; omp_set_num_threads(4); begin = omp_get_wtime(); #pragma omp parallel for reduction(+:sum) schedule(static) for (i=0; i < VECLEN; i+=1) { sum = sum + (a[i]*b[i]); } time_spent = (double)(omp_get_wtime() - begin); printf("Sum = %f\n",sum); printf ("Time: %f\n", time_spent); }
Sema.h
//===--- Sema.h - Semantic Analysis & AST Building --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines the Sema class, which performs semantic analysis and // builds ASTs. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_SEMA_SEMA_H #define LLVM_CLANG_SEMA_SEMA_H #include "clang/AST/ASTConcept.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/Attr.h" #include "clang/AST/Availability.h" #include "clang/AST/ComparisonCategories.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprConcepts.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/ExprOpenMP.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/LocInfoType.h" #include "clang/AST/MangleNumberingContext.h" #include "clang/AST/NSAPI.h" #include "clang/AST/PrettyPrinter.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TypeLoc.h" #include "clang/AST/TypeOrdering.h" #include "clang/Basic/BitmaskEnum.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/DarwinSDKInfo.h" #include "clang/Basic/DiagnosticSema.h" #include "clang/Basic/ExpressionTraits.h" #include "clang/Basic/Module.h" #include "clang/Basic/OpenCLOptions.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/PragmaKinds.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TemplateKinds.h" #include "clang/Basic/TypeTraits.h" #include "clang/Sema/AnalysisBasedWarnings.h" #include "clang/Sema/CleanupInfo.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/ExternalSemaSource.h" #include "clang/Sema/IdentifierResolver.h" #include "clang/Sema/ObjCMethodList.h" #include "clang/Sema/Ownership.h" #include "clang/Sema/Scope.h" #include "clang/Sema/SemaConcept.h" #include "clang/Sema/TypoCorrection.h" #include "clang/Sema/Weak.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include <deque> #include <memory> #include <string> #include <tuple> #include <vector> namespace llvm { class APSInt; template <typename ValueT, typename ValueInfoT> class DenseSet; class SmallBitVector; struct InlineAsmIdentifierInfo; } namespace clang { class ADLResult; class ASTConsumer; class ASTContext; class ASTMutationListener; class ASTReader; class ASTWriter; class ArrayType; class ParsedAttr; class BindingDecl; class BlockDecl; class CapturedDecl; class CXXBasePath; class CXXBasePaths; class CXXBindTemporaryExpr; typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath; class CXXConstructorDecl; class CXXConversionDecl; class CXXDeleteExpr; class CXXDestructorDecl; class CXXFieldCollector; class CXXMemberCallExpr; class CXXMethodDecl; class CXXScopeSpec; class CXXTemporary; class CXXTryStmt; class CallExpr; class ClassTemplateDecl; class ClassTemplatePartialSpecializationDecl; class ClassTemplateSpecializationDecl; class VarTemplatePartialSpecializationDecl; class CodeCompleteConsumer; class CodeCompletionAllocator; class CodeCompletionTUInfo; class CodeCompletionResult; class CoroutineBodyStmt; class Decl; class DeclAccessPair; class DeclContext; class DeclRefExpr; class DeclaratorDecl; class DeducedTemplateArgument; class DependentDiagnostic; class DesignatedInitExpr; class Designation; class EnableIfAttr; class EnumConstantDecl; class Expr; class ExtVectorType; class FormatAttr; class FriendDecl; class FunctionDecl; class FunctionProtoType; class FunctionTemplateDecl; class ImplicitConversionSequence; typedef MutableArrayRef<ImplicitConversionSequence> ConversionSequenceList; class InitListExpr; class InitializationKind; class InitializationSequence; class InitializedEntity; class IntegerLiteral; class LabelStmt; class LambdaExpr; class LangOptions; class LocalInstantiationScope; class LookupResult; class MacroInfo; typedef ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> ModuleIdPath; class ModuleLoader; class MultiLevelTemplateArgumentList; class NamedDecl; class ObjCCategoryDecl; class ObjCCategoryImplDecl; class ObjCCompatibleAliasDecl; class ObjCContainerDecl; class ObjCImplDecl; class ObjCImplementationDecl; class ObjCInterfaceDecl; class ObjCIvarDecl; template <class T> class ObjCList; class ObjCMessageExpr; class ObjCMethodDecl; class ObjCPropertyDecl; class ObjCProtocolDecl; class OMPThreadPrivateDecl; class OMPRequiresDecl; class OMPDeclareReductionDecl; class OMPDeclareSimdDecl; class OMPClause; struct OMPVarListLocTy; struct OverloadCandidate; enum class OverloadCandidateParamOrder : char; enum OverloadCandidateRewriteKind : unsigned; class OverloadCandidateSet; class OverloadExpr; class ParenListExpr; class ParmVarDecl; class Preprocessor; class PseudoDestructorTypeStorage; class PseudoObjectExpr; class QualType; class StandardConversionSequence; class Stmt; class StringLiteral; class SwitchStmt; class TemplateArgument; class TemplateArgumentList; class TemplateArgumentLoc; class TemplateDecl; class TemplateInstantiationCallback; class TemplateParameterList; class TemplatePartialOrderingContext; class TemplateTemplateParmDecl; class Token; class TypeAliasDecl; class TypedefDecl; class TypedefNameDecl; class TypeLoc; class TypoCorrectionConsumer; class UnqualifiedId; class UnresolvedLookupExpr; class UnresolvedMemberExpr; class UnresolvedSetImpl; class UnresolvedSetIterator; class UsingDecl; class UsingShadowDecl; class ValueDecl; class VarDecl; class VarTemplateSpecializationDecl; class VisibilityAttr; class VisibleDeclConsumer; class IndirectFieldDecl; struct DeductionFailureInfo; class TemplateSpecCandidateSet; namespace sema { class AccessedEntity; class BlockScopeInfo; class Capture; class CapturedRegionScopeInfo; class CapturingScopeInfo; class CompoundScopeInfo; class DelayedDiagnostic; class DelayedDiagnosticPool; class FunctionScopeInfo; class LambdaScopeInfo; class PossiblyUnreachableDiag; class SemaPPCallbacks; class TemplateDeductionInfo; } namespace threadSafety { class BeforeSet; void threadSafetyCleanup(BeforeSet* Cache); } // FIXME: No way to easily map from TemplateTypeParmTypes to // TemplateTypeParmDecls, so we have this horrible PointerUnion. typedef std::pair<llvm::PointerUnion<const TemplateTypeParmType*, NamedDecl*>, SourceLocation> UnexpandedParameterPack; /// Describes whether we've seen any nullability information for the given /// file. struct FileNullability { /// The first pointer declarator (of any pointer kind) in the file that does /// not have a corresponding nullability annotation. SourceLocation PointerLoc; /// The end location for the first pointer declarator in the file. Used for /// placing fix-its. SourceLocation PointerEndLoc; /// Which kind of pointer declarator we saw. uint8_t PointerKind; /// Whether we saw any type nullability annotations in the given file. bool SawTypeNullability = false; }; /// A mapping from file IDs to a record of whether we've seen nullability /// information in that file. class FileNullabilityMap { /// A mapping from file IDs to the nullability information for each file ID. llvm::DenseMap<FileID, FileNullability> Map; /// A single-element cache based on the file ID. struct { FileID File; FileNullability Nullability; } Cache; public: FileNullability &operator[](FileID file) { // Check the single-element cache. if (file == Cache.File) return Cache.Nullability; // It's not in the single-element cache; flush the cache if we have one. if (!Cache.File.isInvalid()) { Map[Cache.File] = Cache.Nullability; } // Pull this entry into the cache. Cache.File = file; Cache.Nullability = Map[file]; return Cache.Nullability; } }; // TODO SYCL Integration header approach relies on an assumption that kernel // lambda objects created by the host compiler and any of the device compilers // will be identical wrt to field types, order and offsets. Some verification // mechanism should be developed to enforce that. // TODO FIXME SYCL Support for SYCL in FE should be refactored: // - kernel identification and generation should be made a separate pass over // AST. RecursiveASTVisitor + VisitFunctionTemplateDecl + // FunctionTemplateDecl::getSpecializations() mechanism could be used for that. // - All SYCL stuff on Sema level should be encapsulated into a single Sema // field // - Move SYCL stuff into a separate header // Represents contents of a SYCL integration header file produced by a SYCL // device compiler and used by SYCL host compiler (via forced inclusion into // compiled SYCL source): // - SYCL kernel names // - SYCL kernel parameters and offsets of corresponding actual arguments class SYCLIntegrationHeader { public: // Kind of kernel's parameters as captured by the compiler in the // kernel lambda or function object enum kernel_param_kind_t { kind_first, kind_accessor = kind_first, kind_std_layout, kind_sampler, kind_pointer, kind_specialization_constants_buffer, kind_stream, kind_last = kind_stream }; public: SYCLIntegrationHeader(Sema &S); /// Emits contents of the header into given stream. void emit(raw_ostream &Out); /// Emits contents of the header into a file with given name. /// Returns true/false on success/failure. bool emit(StringRef MainSrc); /// Signals that subsequent parameter descriptor additions will go to /// the kernel with given name. Starts new kernel invocation descriptor. void startKernel(const FunctionDecl *SyclKernel, QualType KernelNameType, SourceLocation Loc, bool IsESIMD, bool IsUnnamedKernel); /// Adds a kernel parameter descriptor to current kernel invocation /// descriptor. void addParamDesc(kernel_param_kind_t Kind, int Info, unsigned Offset); /// Signals that addition of parameter descriptors to current kernel /// invocation descriptor has finished. void endKernel(); /// Registers a specialization constant to emit info for it into the header. void addSpecConstant(StringRef IDName, QualType IDType); /// Update the names of a kernel description based on its SyclKernel. void updateKernelNames(const FunctionDecl *SyclKernel, StringRef Name, StringRef StableName) { auto Itr = llvm::find_if(KernelDescs, [SyclKernel](const KernelDesc &KD) { return KD.SyclKernel == SyclKernel; }); assert(Itr != KernelDescs.end() && "Unknown kernel description"); Itr->updateKernelNames(Name, StableName); } private: // Kernel actual parameter descriptor. struct KernelParamDesc { // Represents a parameter kind. kernel_param_kind_t Kind = kind_last; // If Kind is kind_scalar or kind_struct, then // denotes parameter size in bytes (includes padding for structs) // If Kind is kind_accessor // denotes access target; possible access targets are defined in // access/access.hpp int Info = 0; // Offset of the captured parameter value in the lambda or function object. unsigned Offset = 0; KernelParamDesc() = default; }; // Kernel invocation descriptor struct KernelDesc { /// sycl_kernel function associated with this kernel. const FunctionDecl *SyclKernel; /// Kernel name. std::string Name; /// Kernel name type. QualType NameType; /// Kernel name with stable lambda name mangling std::string StableName; SourceLocation KernelLocation; /// Whether this kernel is an ESIMD one. bool IsESIMDKernel; /// Descriptor of kernel actual parameters. SmallVector<KernelParamDesc, 8> Params; // If we are in unnamed kernel/lambda mode AND this is one that the user // hasn't provided an explicit name for. bool IsUnnamedKernel; KernelDesc(const FunctionDecl *SyclKernel, QualType NameType, SourceLocation KernelLoc, bool IsESIMD, bool IsUnnamedKernel) : SyclKernel(SyclKernel), NameType(NameType), KernelLocation(KernelLoc), IsESIMDKernel(IsESIMD), IsUnnamedKernel(IsUnnamedKernel) {} void updateKernelNames(StringRef Name, StringRef StableName) { this->Name = Name.str(); this->StableName = StableName.str(); } }; /// Returns the latest invocation descriptor started by /// SYCLIntegrationHeader::startKernel KernelDesc *getCurKernelDesc() { return KernelDescs.size() > 0 ? &KernelDescs[KernelDescs.size() - 1] : nullptr; } private: /// Keeps invocation descriptors for each kernel invocation started by /// SYCLIntegrationHeader::startKernel SmallVector<KernelDesc, 4> KernelDescs; using SpecConstID = std::pair<QualType, std::string>; /// Keeps specialization constants met in the translation unit. Maps spec /// constant's ID type to generated unique name. Duplicates are removed at /// integration header emission time. llvm::SmallVector<SpecConstID, 4> SpecConsts; Sema &S; }; class SYCLIntegrationFooter { public: SYCLIntegrationFooter(Sema &S) : S(S) {} bool emit(StringRef MainSrc); void addVarDecl(const VarDecl *VD); private: bool emit(raw_ostream &O); Sema &S; llvm::SmallVector<const VarDecl *> SpecConstants; void emitSpecIDName(raw_ostream &O, const VarDecl *VD); }; /// Tracks expected type during expression parsing, for use in code completion. /// 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 avoids updating the type on hot paths in the parser. class PreferredTypeBuilder { public: PreferredTypeBuilder(bool Enabled) : Enabled(Enabled) {} void enterCondition(Sema &S, SourceLocation Tok); void enterReturn(Sema &S, SourceLocation Tok); void enterVariableInit(SourceLocation Tok, Decl *D); /// Handles e.g. BaseType{ .D = Tok... void enterDesignatedInitializer(SourceLocation Tok, QualType BaseType, const Designation &D); /// Computing a type for the function argument may require running /// overloading, so we postpone its computation until it is actually needed. /// /// Clients should be very careful when using this funciton, as it stores a /// function_ref, clients should make sure all calls to get() with the same /// location happen while function_ref is alive. /// /// The callback should also emit signature help as a side-effect, but only /// if the completion point has been reached. void enterFunctionArgument(SourceLocation Tok, llvm::function_ref<QualType()> ComputeType); void enterParenExpr(SourceLocation Tok, SourceLocation LParLoc); void enterUnary(Sema &S, SourceLocation Tok, tok::TokenKind OpKind, SourceLocation OpLoc); void enterBinary(Sema &S, SourceLocation Tok, Expr *LHS, tok::TokenKind Op); void enterMemAccess(Sema &S, SourceLocation Tok, Expr *Base); void enterSubscript(Sema &S, SourceLocation Tok, Expr *LHS); /// Handles all type casts, including C-style cast, C++ casts, etc. void enterTypeCast(SourceLocation Tok, QualType CastType); /// Get the expected type associated with this location, if any. /// /// If the location is a function argument, determining the expected type /// involves considering all function overloads and the arguments so far. /// In this case, signature help for these function overloads will be reported /// as a side-effect (only if the completion point has been reached). QualType get(SourceLocation Tok) const { if (!Enabled || Tok != ExpectedLoc) return QualType(); if (!Type.isNull()) return Type; if (ComputeType) return ComputeType(); return QualType(); } private: bool Enabled; /// Start position of a token for which we store expected type. SourceLocation ExpectedLoc; /// Expected type for a token starting at ExpectedLoc. QualType Type; /// A function to compute expected type at ExpectedLoc. It is only considered /// if Type is null. llvm::function_ref<QualType()> ComputeType; }; /// Sema - This implements semantic analysis and AST building for C. class Sema final { Sema(const Sema &) = delete; void operator=(const Sema &) = delete; ///Source of additional semantic information. ExternalSemaSource *ExternalSource; ///Whether Sema has generated a multiplexer and has to delete it. bool isMultiplexExternalSource; static bool mightHaveNonExternalLinkage(const DeclaratorDecl *FD); bool isVisibleSlow(const NamedDecl *D); /// Determine whether two declarations should be linked together, given that /// the old declaration might not be visible and the new declaration might /// not have external linkage. bool shouldLinkPossiblyHiddenDecl(const NamedDecl *Old, const NamedDecl *New) { if (isVisible(Old)) return true; // See comment in below overload for why it's safe to compute the linkage // of the new declaration here. if (New->isExternallyDeclarable()) { assert(Old->isExternallyDeclarable() && "should not have found a non-externally-declarable previous decl"); return true; } return false; } bool shouldLinkPossiblyHiddenDecl(LookupResult &Old, const NamedDecl *New); void setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem, QualType ResultTy, ArrayRef<QualType> Args); public: /// The maximum alignment, same as in llvm::Value. We duplicate them here /// because that allows us not to duplicate the constants in clang code, /// which we must to since we can't directly use the llvm constants. /// The value is verified against llvm here: lib/CodeGen/CGDecl.cpp /// /// This is the greatest alignment value supported by load, store, and alloca /// instructions, and global values. static const unsigned MaxAlignmentExponent = 32; static const uint64_t MaximumAlignment = 1ull << MaxAlignmentExponent; typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef OpaquePtr<QualType> TypeTy; OpenCLOptions OpenCLFeatures; FPOptions CurFPFeatures; const LangOptions &LangOpts; Preprocessor &PP; ASTContext &Context; ASTConsumer &Consumer; DiagnosticsEngine &Diags; SourceManager &SourceMgr; /// Flag indicating whether or not to collect detailed statistics. bool CollectStats; /// Code-completion consumer. CodeCompleteConsumer *CodeCompleter; /// CurContext - This is the current declaration context of parsing. DeclContext *CurContext; /// Generally null except when we temporarily switch decl contexts, /// like in \see ActOnObjCTemporaryExitContainerContext. DeclContext *OriginalLexicalContext; /// VAListTagName - The declaration name corresponding to __va_list_tag. /// This is used as part of a hack to omit that class from ADL results. DeclarationName VAListTagName; bool MSStructPragmaOn; // True when \#pragma ms_struct on /// Controls member pointer representation format under the MS ABI. LangOptions::PragmaMSPointersToMembersKind MSPointerToMemberRepresentationMethod; /// Stack of active SEH __finally scopes. Can be empty. SmallVector<Scope*, 2> CurrentSEHFinally; /// Source location for newly created implicit MSInheritanceAttrs SourceLocation ImplicitMSInheritanceAttrLoc; /// Holds TypoExprs that are created from `createDelayedTypo`. This is used by /// `TransformTypos` in order to keep track of any TypoExprs that are created /// recursively during typo correction and wipe them away if the correction /// fails. llvm::SmallVector<TypoExpr *, 2> TypoExprs; /// pragma clang section kind enum PragmaClangSectionKind { PCSK_Invalid = 0, PCSK_BSS = 1, PCSK_Data = 2, PCSK_Rodata = 3, PCSK_Text = 4, PCSK_Relro = 5 }; enum PragmaClangSectionAction { PCSA_Set = 0, PCSA_Clear = 1 }; struct PragmaClangSection { std::string SectionName; bool Valid = false; SourceLocation PragmaLocation; }; PragmaClangSection PragmaClangBSSSection; PragmaClangSection PragmaClangDataSection; PragmaClangSection PragmaClangRodataSection; PragmaClangSection PragmaClangRelroSection; PragmaClangSection PragmaClangTextSection; enum PragmaMsStackAction { PSK_Reset = 0x0, // #pragma () PSK_Set = 0x1, // #pragma (value) PSK_Push = 0x2, // #pragma (push[, id]) PSK_Pop = 0x4, // #pragma (pop[, id]) PSK_Show = 0x8, // #pragma (show) -- only for "pack"! PSK_Push_Set = PSK_Push | PSK_Set, // #pragma (push[, id], value) PSK_Pop_Set = PSK_Pop | PSK_Set, // #pragma (pop[, id], value) }; // #pragma pack and align. class AlignPackInfo { public: // `Native` represents default align mode, which may vary based on the // platform. enum Mode : unsigned char { Native, Natural, Packed, Mac68k }; // #pragma pack info constructor AlignPackInfo(AlignPackInfo::Mode M, unsigned Num, bool IsXL) : PackAttr(true), AlignMode(M), PackNumber(Num), XLStack(IsXL) { assert(Num == PackNumber && "The pack number has been truncated."); } // #pragma align info constructor AlignPackInfo(AlignPackInfo::Mode M, bool IsXL) : PackAttr(false), AlignMode(M), PackNumber(M == Packed ? 1 : UninitPackVal), XLStack(IsXL) {} explicit AlignPackInfo(bool IsXL) : AlignPackInfo(Native, IsXL) {} AlignPackInfo() : AlignPackInfo(Native, false) {} // When a AlignPackInfo itself cannot be used, this returns an 32-bit // integer encoding for it. This should only be passed to // AlignPackInfo::getFromRawEncoding, it should not be inspected directly. static uint32_t getRawEncoding(const AlignPackInfo &Info) { std::uint32_t Encoding{}; if (Info.IsXLStack()) Encoding |= IsXLMask; Encoding |= static_cast<uint32_t>(Info.getAlignMode()) << 1; if (Info.IsPackAttr()) Encoding |= PackAttrMask; Encoding |= static_cast<uint32_t>(Info.getPackNumber()) << 4; return Encoding; } static AlignPackInfo getFromRawEncoding(unsigned Encoding) { bool IsXL = static_cast<bool>(Encoding & IsXLMask); AlignPackInfo::Mode M = static_cast<AlignPackInfo::Mode>((Encoding & AlignModeMask) >> 1); int PackNumber = (Encoding & PackNumMask) >> 4; if (Encoding & PackAttrMask) return AlignPackInfo(M, PackNumber, IsXL); return AlignPackInfo(M, IsXL); } bool IsPackAttr() const { return PackAttr; } bool IsAlignAttr() const { return !PackAttr; } Mode getAlignMode() const { return AlignMode; } unsigned getPackNumber() const { return PackNumber; } bool IsPackSet() const { // #pragma align, #pragma pack(), and #pragma pack(0) do not set the pack // attriute on a decl. return PackNumber != UninitPackVal && PackNumber != 0; } bool IsXLStack() const { return XLStack; } bool operator==(const AlignPackInfo &Info) const { return std::tie(AlignMode, PackNumber, PackAttr, XLStack) == std::tie(Info.AlignMode, Info.PackNumber, Info.PackAttr, Info.XLStack); } bool operator!=(const AlignPackInfo &Info) const { return !(*this == Info); } private: /// \brief True if this is a pragma pack attribute, /// not a pragma align attribute. bool PackAttr; /// \brief The alignment mode that is in effect. Mode AlignMode; /// \brief The pack number of the stack. unsigned char PackNumber; /// \brief True if it is a XL #pragma align/pack stack. bool XLStack; /// \brief Uninitialized pack value. static constexpr unsigned char UninitPackVal = -1; // Masks to encode and decode an AlignPackInfo. static constexpr uint32_t IsXLMask{0x0000'0001}; static constexpr uint32_t AlignModeMask{0x0000'0006}; static constexpr uint32_t PackAttrMask{0x00000'0008}; static constexpr uint32_t PackNumMask{0x0000'01F0}; }; template<typename ValueType> struct PragmaStack { struct Slot { llvm::StringRef StackSlotLabel; ValueType Value; SourceLocation PragmaLocation; SourceLocation PragmaPushLocation; Slot(llvm::StringRef StackSlotLabel, ValueType Value, SourceLocation PragmaLocation, SourceLocation PragmaPushLocation) : StackSlotLabel(StackSlotLabel), Value(Value), PragmaLocation(PragmaLocation), PragmaPushLocation(PragmaPushLocation) {} }; void Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, ValueType Value) { if (Action == PSK_Reset) { CurrentValue = DefaultValue; CurrentPragmaLocation = PragmaLocation; return; } if (Action & PSK_Push) Stack.emplace_back(StackSlotLabel, CurrentValue, CurrentPragmaLocation, PragmaLocation); else if (Action & PSK_Pop) { if (!StackSlotLabel.empty()) { // If we've got a label, try to find it and jump there. auto I = llvm::find_if(llvm::reverse(Stack), [&](const Slot &x) { return x.StackSlotLabel == StackSlotLabel; }); // If we found the label so pop from there. if (I != Stack.rend()) { CurrentValue = I->Value; CurrentPragmaLocation = I->PragmaLocation; Stack.erase(std::prev(I.base()), Stack.end()); } } else if (!Stack.empty()) { // We do not have a label, just pop the last entry. CurrentValue = Stack.back().Value; CurrentPragmaLocation = Stack.back().PragmaLocation; Stack.pop_back(); } } if (Action & PSK_Set) { CurrentValue = Value; CurrentPragmaLocation = PragmaLocation; } } // MSVC seems to add artificial slots to #pragma stacks on entering a C++ // method body to restore the stacks on exit, so it works like this: // // struct S { // #pragma <name>(push, InternalPragmaSlot, <current_pragma_value>) // void Method {} // #pragma <name>(pop, InternalPragmaSlot) // }; // // It works even with #pragma vtordisp, although MSVC doesn't support // #pragma vtordisp(push [, id], n) // syntax. // // Push / pop a named sentinel slot. void SentinelAction(PragmaMsStackAction Action, StringRef Label) { assert((Action == PSK_Push || Action == PSK_Pop) && "Can only push / pop #pragma stack sentinels!"); Act(CurrentPragmaLocation, Action, Label, CurrentValue); } // Constructors. explicit PragmaStack(const ValueType &Default) : DefaultValue(Default), CurrentValue(Default) {} bool hasValue() const { return CurrentValue != DefaultValue; } SmallVector<Slot, 2> Stack; ValueType DefaultValue; // Value used for PSK_Reset action. ValueType CurrentValue; SourceLocation CurrentPragmaLocation; }; // FIXME: We should serialize / deserialize these if they occur in a PCH (but // we shouldn't do so if they're in a module). /// Whether to insert vtordisps prior to virtual bases in the Microsoft /// C++ ABI. Possible values are 0, 1, and 2, which mean: /// /// 0: Suppress all vtordisps /// 1: Insert vtordisps in the presence of vbase overrides and non-trivial /// structors /// 2: Always insert vtordisps to support RTTI on partially constructed /// objects PragmaStack<MSVtorDispMode> VtorDispStack; PragmaStack<AlignPackInfo> AlignPackStack; // The current #pragma align/pack values and locations at each #include. struct AlignPackIncludeState { AlignPackInfo CurrentValue; SourceLocation CurrentPragmaLocation; bool HasNonDefaultValue, ShouldWarnOnInclude; }; SmallVector<AlignPackIncludeState, 8> AlignPackIncludeStack; // Segment #pragmas. PragmaStack<StringLiteral *> DataSegStack; PragmaStack<StringLiteral *> BSSSegStack; PragmaStack<StringLiteral *> ConstSegStack; PragmaStack<StringLiteral *> CodeSegStack; // This stack tracks the current state of Sema.CurFPFeatures. PragmaStack<FPOptionsOverride> FpPragmaStack; FPOptionsOverride CurFPFeatureOverrides() { FPOptionsOverride result; if (!FpPragmaStack.hasValue()) { result = FPOptionsOverride(); } else { result = FpPragmaStack.CurrentValue; } return result; } // RAII object to push / pop sentinel slots for all MS #pragma stacks. // Actions should be performed only if we enter / exit a C++ method body. class PragmaStackSentinelRAII { public: PragmaStackSentinelRAII(Sema &S, StringRef SlotLabel, bool ShouldAct); ~PragmaStackSentinelRAII(); private: Sema &S; StringRef SlotLabel; bool ShouldAct; }; /// A mapping that describes the nullability we've seen in each header file. FileNullabilityMap NullabilityMap; /// Last section used with #pragma init_seg. StringLiteral *CurInitSeg; SourceLocation CurInitSegLoc; /// VisContext - Manages the stack for \#pragma GCC visibility. void *VisContext; // Really a "PragmaVisStack*" /// This an attribute introduced by \#pragma clang attribute. struct PragmaAttributeEntry { SourceLocation Loc; ParsedAttr *Attribute; SmallVector<attr::SubjectMatchRule, 4> MatchRules; bool IsUsed; }; /// A push'd group of PragmaAttributeEntries. struct PragmaAttributeGroup { /// The location of the push attribute. SourceLocation Loc; /// The namespace of this push group. const IdentifierInfo *Namespace; SmallVector<PragmaAttributeEntry, 2> Entries; }; SmallVector<PragmaAttributeGroup, 2> PragmaAttributeStack; /// The declaration that is currently receiving an attribute from the /// #pragma attribute stack. const Decl *PragmaAttributeCurrentTargetDecl; /// This represents the last location of a "#pragma clang optimize off" /// directive if such a directive has not been closed by an "on" yet. If /// optimizations are currently "on", this is set to an invalid location. SourceLocation OptimizeOffPragmaLocation; /// Flag indicating if Sema is building a recovery call expression. /// /// This flag is used to avoid building recovery call expressions /// if Sema is already doing so, which would cause infinite recursions. bool IsBuildingRecoveryCallExpr; /// Used to control the generation of ExprWithCleanups. CleanupInfo Cleanup; /// ExprCleanupObjects - This is the stack of objects requiring /// cleanup that are created by the current full expression. SmallVector<ExprWithCleanups::CleanupObject, 8> ExprCleanupObjects; /// Store a set of either DeclRefExprs or MemberExprs that contain a reference /// to a variable (constant) that may or may not be odr-used in this Expr, and /// we won't know until all lvalue-to-rvalue and discarded value conversions /// have been applied to all subexpressions of the enclosing full expression. /// This is cleared at the end of each full expression. using MaybeODRUseExprSet = llvm::SetVector<Expr *, SmallVector<Expr *, 4>, llvm::SmallPtrSet<Expr *, 4>>; MaybeODRUseExprSet MaybeODRUseExprs; std::unique_ptr<sema::FunctionScopeInfo> CachedFunctionScope; /// Stack containing information about each of the nested /// function, block, and method scopes that are currently active. SmallVector<sema::FunctionScopeInfo *, 4> FunctionScopes; /// The index of the first FunctionScope that corresponds to the current /// context. unsigned FunctionScopesStart = 0; ArrayRef<sema::FunctionScopeInfo*> getFunctionScopes() const { return llvm::makeArrayRef(FunctionScopes.begin() + FunctionScopesStart, FunctionScopes.end()); } /// Stack containing information needed when in C++2a an 'auto' is encountered /// in a function declaration parameter type specifier in order to invent a /// corresponding template parameter in the enclosing abbreviated function /// template. This information is also present in LambdaScopeInfo, stored in /// the FunctionScopes stack. SmallVector<InventedTemplateParameterInfo, 4> InventedParameterInfos; /// The index of the first InventedParameterInfo that refers to the current /// context. unsigned InventedParameterInfosStart = 0; ArrayRef<InventedTemplateParameterInfo> getInventedParameterInfos() const { return llvm::makeArrayRef(InventedParameterInfos.begin() + InventedParameterInfosStart, InventedParameterInfos.end()); } typedef LazyVector<TypedefNameDecl *, ExternalSemaSource, &ExternalSemaSource::ReadExtVectorDecls, 2, 2> ExtVectorDeclsType; /// ExtVectorDecls - This is a list all the extended vector types. This allows /// us to associate a raw vector type with one of the ext_vector type names. /// This is only necessary for issuing pretty diagnostics. ExtVectorDeclsType ExtVectorDecls; /// FieldCollector - Collects CXXFieldDecls during parsing of C++ classes. std::unique_ptr<CXXFieldCollector> FieldCollector; typedef llvm::SmallSetVector<NamedDecl *, 16> NamedDeclSetType; /// Set containing all declared private fields that are not used. NamedDeclSetType UnusedPrivateFields; /// Set containing all typedefs that are likely unused. llvm::SmallSetVector<const TypedefNameDecl *, 4> UnusedLocalTypedefNameCandidates; /// Delete-expressions to be analyzed at the end of translation unit /// /// This list contains class members, and locations of delete-expressions /// that could not be proven as to whether they mismatch with new-expression /// used in initializer of the field. typedef std::pair<SourceLocation, bool> DeleteExprLoc; typedef llvm::SmallVector<DeleteExprLoc, 4> DeleteLocs; llvm::MapVector<FieldDecl *, DeleteLocs> DeleteExprs; typedef llvm::SmallPtrSet<const CXXRecordDecl*, 8> RecordDeclSetTy; /// PureVirtualClassDiagSet - a set of class declarations which we have /// emitted a list of pure virtual functions. Used to prevent emitting the /// same list more than once. std::unique_ptr<RecordDeclSetTy> PureVirtualClassDiagSet; /// ParsingInitForAutoVars - a set of declarations with auto types for which /// we are currently parsing the initializer. llvm::SmallPtrSet<const Decl*, 4> ParsingInitForAutoVars; /// Look for a locally scoped extern "C" declaration by the given name. NamedDecl *findLocallyScopedExternCDecl(DeclarationName Name); typedef LazyVector<VarDecl *, ExternalSemaSource, &ExternalSemaSource::ReadTentativeDefinitions, 2, 2> TentativeDefinitionsType; /// All the tentative definitions encountered in the TU. TentativeDefinitionsType TentativeDefinitions; /// All the external declarations encoutered and used in the TU. SmallVector<VarDecl *, 4> ExternalDeclarations; typedef LazyVector<const DeclaratorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadUnusedFileScopedDecls, 2, 2> UnusedFileScopedDeclsType; /// The set of file scoped decls seen so far that have not been used /// and must warn if not used. Only contains the first declaration. UnusedFileScopedDeclsType UnusedFileScopedDecls; typedef LazyVector<CXXConstructorDecl *, ExternalSemaSource, &ExternalSemaSource::ReadDelegatingConstructors, 2, 2> DelegatingCtorDeclsType; /// All the delegating constructors seen so far in the file, used for /// cycle detection at the end of the TU. DelegatingCtorDeclsType DelegatingCtorDecls; /// All the overriding functions seen during a class definition /// that had their exception spec checks delayed, plus the overridden /// function. SmallVector<std::pair<const CXXMethodDecl*, const CXXMethodDecl*>, 2> DelayedOverridingExceptionSpecChecks; /// All the function redeclarations seen during a class definition that had /// their exception spec checks delayed, plus the prior declaration they /// should be checked against. Except during error recovery, the new decl /// should always be a friend declaration, as that's the only valid way to /// redeclare a special member before its class is complete. SmallVector<std::pair<FunctionDecl*, FunctionDecl*>, 2> DelayedEquivalentExceptionSpecChecks; typedef llvm::MapVector<const FunctionDecl *, std::unique_ptr<LateParsedTemplate>> LateParsedTemplateMapT; LateParsedTemplateMapT LateParsedTemplateMap; /// Callback to the parser to parse templated functions when needed. typedef void LateTemplateParserCB(void *P, LateParsedTemplate &LPT); typedef void LateTemplateParserCleanupCB(void *P); LateTemplateParserCB *LateTemplateParser; LateTemplateParserCleanupCB *LateTemplateParserCleanup; void *OpaqueParser; void SetLateTemplateParser(LateTemplateParserCB *LTP, LateTemplateParserCleanupCB *LTPCleanup, void *P) { LateTemplateParser = LTP; LateTemplateParserCleanup = LTPCleanup; OpaqueParser = P; } class DelayedDiagnostics; class DelayedDiagnosticsState { sema::DelayedDiagnosticPool *SavedPool; friend class Sema::DelayedDiagnostics; }; typedef DelayedDiagnosticsState ParsingDeclState; typedef DelayedDiagnosticsState ProcessingContextState; /// A class which encapsulates the logic for delaying diagnostics /// during parsing and other processing. class DelayedDiagnostics { /// The current pool of diagnostics into which delayed /// diagnostics should go. sema::DelayedDiagnosticPool *CurPool; public: DelayedDiagnostics() : CurPool(nullptr) {} /// Adds a delayed diagnostic. void add(const sema::DelayedDiagnostic &diag); // in DelayedDiagnostic.h /// Determines whether diagnostics should be delayed. bool shouldDelayDiagnostics() { return CurPool != nullptr; } /// Returns the current delayed-diagnostics pool. sema::DelayedDiagnosticPool *getCurrentPool() const { return CurPool; } /// Enter a new scope. Access and deprecation diagnostics will be /// collected in this pool. DelayedDiagnosticsState push(sema::DelayedDiagnosticPool &pool) { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = &pool; return state; } /// Leave a delayed-diagnostic state that was previously pushed. /// Do not emit any of the diagnostics. This is performed as part /// of the bookkeeping of popping a pool "properly". void popWithoutEmitting(DelayedDiagnosticsState state) { CurPool = state.SavedPool; } /// Enter a new scope where access and deprecation diagnostics are /// not delayed. DelayedDiagnosticsState pushUndelayed() { DelayedDiagnosticsState state; state.SavedPool = CurPool; CurPool = nullptr; return state; } /// Undo a previous pushUndelayed(). void popUndelayed(DelayedDiagnosticsState state) { assert(CurPool == nullptr); CurPool = state.SavedPool; } } DelayedDiagnostics; /// A RAII object to temporarily push a declaration context. class ContextRAII { private: Sema &S; DeclContext *SavedContext; ProcessingContextState SavedContextState; QualType SavedCXXThisTypeOverride; unsigned SavedFunctionScopesStart; unsigned SavedInventedParameterInfosStart; public: ContextRAII(Sema &S, DeclContext *ContextToPush, bool NewThisContext = true) : S(S), SavedContext(S.CurContext), SavedContextState(S.DelayedDiagnostics.pushUndelayed()), SavedCXXThisTypeOverride(S.CXXThisTypeOverride), SavedFunctionScopesStart(S.FunctionScopesStart), SavedInventedParameterInfosStart(S.InventedParameterInfosStart) { assert(ContextToPush && "pushing null context"); S.CurContext = ContextToPush; if (NewThisContext) S.CXXThisTypeOverride = QualType(); // Any saved FunctionScopes do not refer to this context. S.FunctionScopesStart = S.FunctionScopes.size(); S.InventedParameterInfosStart = S.InventedParameterInfos.size(); } void pop() { if (!SavedContext) return; S.CurContext = SavedContext; S.DelayedDiagnostics.popUndelayed(SavedContextState); S.CXXThisTypeOverride = SavedCXXThisTypeOverride; S.FunctionScopesStart = SavedFunctionScopesStart; S.InventedParameterInfosStart = SavedInventedParameterInfosStart; SavedContext = nullptr; } ~ContextRAII() { pop(); } }; /// Whether the AST is currently being rebuilt to correct immediate /// invocations. Immediate invocation candidates and references to consteval /// functions aren't tracked when this is set. bool RebuildingImmediateInvocation = false; /// Used to change context to isConstantEvaluated without pushing a heavy /// ExpressionEvaluationContextRecord object. bool isConstantEvaluatedOverride; bool isConstantEvaluated() { return ExprEvalContexts.back().isConstantEvaluated() || isConstantEvaluatedOverride; } /// RAII object to handle the state changes required to synthesize /// a function body. class SynthesizedFunctionScope { Sema &S; Sema::ContextRAII SavedContext; bool PushedCodeSynthesisContext = false; public: SynthesizedFunctionScope(Sema &S, DeclContext *DC) : S(S), SavedContext(S, DC) { S.PushFunctionScope(); S.PushExpressionEvaluationContext( Sema::ExpressionEvaluationContext::PotentiallyEvaluated); if (auto *FD = dyn_cast<FunctionDecl>(DC)) FD->setWillHaveBody(true); else assert(isa<ObjCMethodDecl>(DC)); } void addContextNote(SourceLocation UseLoc) { assert(!PushedCodeSynthesisContext); Sema::CodeSynthesisContext Ctx; Ctx.Kind = Sema::CodeSynthesisContext::DefiningSynthesizedFunction; Ctx.PointOfInstantiation = UseLoc; Ctx.Entity = cast<Decl>(S.CurContext); S.pushCodeSynthesisContext(Ctx); PushedCodeSynthesisContext = true; } ~SynthesizedFunctionScope() { if (PushedCodeSynthesisContext) S.popCodeSynthesisContext(); if (auto *FD = dyn_cast<FunctionDecl>(S.CurContext)) FD->setWillHaveBody(false); S.PopExpressionEvaluationContext(); S.PopFunctionScopeInfo(); } }; /// WeakUndeclaredIdentifiers - Identifiers contained in /// \#pragma weak before declared. rare. may alias another /// identifier, declared or undeclared llvm::MapVector<IdentifierInfo *, WeakInfo> WeakUndeclaredIdentifiers; /// ExtnameUndeclaredIdentifiers - Identifiers contained in /// \#pragma redefine_extname before declared. Used in Solaris system headers /// to define functions that occur in multiple standards to call the version /// in the currently selected standard. llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*> ExtnameUndeclaredIdentifiers; /// Load weak undeclared identifiers from the external source. void LoadExternalWeakUndeclaredIdentifiers(); /// WeakTopLevelDecl - Translation-unit scoped declarations generated by /// \#pragma weak during processing of other Decls. /// I couldn't figure out a clean way to generate these in-line, so /// we store them here and handle separately -- which is a hack. /// It would be best to refactor this. SmallVector<Decl*,2> WeakTopLevelDecl; IdentifierResolver IdResolver; /// Translation Unit Scope - useful to Objective-C actions that need /// to lookup file scope declarations in the "ordinary" C decl namespace. /// For example, user-defined classes, built-in "id" type, etc. Scope *TUScope; /// The C++ "std" namespace, where the standard library resides. LazyDeclPtr StdNamespace; /// The C++ "std::bad_alloc" class, which is defined by the C++ /// standard library. LazyDeclPtr StdBadAlloc; /// The C++ "std::align_val_t" enum class, which is defined by the C++ /// standard library. LazyDeclPtr StdAlignValT; /// The C++ "std::experimental" namespace, where the experimental parts /// of the standard library resides. NamespaceDecl *StdExperimentalNamespaceCache; /// The C++ "std::initializer_list" template, which is defined in /// \<initializer_list>. ClassTemplateDecl *StdInitializerList; /// The C++ "std::coroutine_traits" template, which is defined in /// \<coroutine_traits> ClassTemplateDecl *StdCoroutineTraitsCache; /// The namespace where coroutine components are defined. In standard, /// they are defined in std namespace. And in the previous implementation, /// they are defined in std::experimental namespace. NamespaceDecl *CoroTraitsNamespaceCache; /// The C++ "type_info" declaration, which is defined in \<typeinfo>. RecordDecl *CXXTypeInfoDecl; /// The MSVC "_GUID" struct, which is defined in MSVC header files. RecordDecl *MSVCGuidDecl; /// Caches identifiers/selectors for NSFoundation APIs. std::unique_ptr<NSAPI> NSAPIObj; /// The declaration of the Objective-C NSNumber class. ObjCInterfaceDecl *NSNumberDecl; /// The declaration of the Objective-C NSValue class. ObjCInterfaceDecl *NSValueDecl; /// Pointer to NSNumber type (NSNumber *). QualType NSNumberPointer; /// Pointer to NSValue type (NSValue *). QualType NSValuePointer; /// The Objective-C NSNumber methods used to create NSNumber literals. ObjCMethodDecl *NSNumberLiteralMethods[NSAPI::NumNSNumberLiteralMethods]; /// The declaration of the Objective-C NSString class. ObjCInterfaceDecl *NSStringDecl; /// Pointer to NSString type (NSString *). QualType NSStringPointer; /// The declaration of the stringWithUTF8String: method. ObjCMethodDecl *StringWithUTF8StringMethod; /// The declaration of the valueWithBytes:objCType: method. ObjCMethodDecl *ValueWithBytesObjCTypeMethod; /// The declaration of the Objective-C NSArray class. ObjCInterfaceDecl *NSArrayDecl; /// The declaration of the arrayWithObjects:count: method. ObjCMethodDecl *ArrayWithObjectsMethod; /// The declaration of the Objective-C NSDictionary class. ObjCInterfaceDecl *NSDictionaryDecl; /// The declaration of the dictionaryWithObjects:forKeys:count: method. ObjCMethodDecl *DictionaryWithObjectsMethod; /// id<NSCopying> type. QualType QIDNSCopying; /// will hold 'respondsToSelector:' Selector RespondsToSelectorSel; /// A flag to remember whether the implicit forms of operator new and delete /// have been declared. bool GlobalNewDeleteDeclared; /// Describes how the expressions currently being parsed are /// evaluated at run-time, if at all. enum class ExpressionEvaluationContext { /// The current expression and its subexpressions occur within an /// unevaluated operand (C++11 [expr]p7), such as the subexpression of /// \c sizeof, where the type of the expression may be significant but /// no code will be generated to evaluate the value of the expression at /// run time. Unevaluated, /// The current expression occurs within a braced-init-list within /// an unevaluated operand. This is mostly like a regular unevaluated /// context, except that we still instantiate constexpr functions that are /// referenced here so that we can perform narrowing checks correctly. UnevaluatedList, /// The current expression occurs within a discarded statement. /// This behaves largely similarly to an unevaluated operand in preventing /// definitions from being required, but not in other ways. DiscardedStatement, /// The current expression occurs within an unevaluated /// operand that unconditionally permits abstract references to /// fields, such as a SIZE operator in MS-style inline assembly. UnevaluatedAbstract, /// The current context is "potentially evaluated" in C++11 terms, /// but the expression is evaluated at compile-time (like the values of /// cases in a switch statement). ConstantEvaluated, /// In addition of being constant evaluated, the current expression /// occurs in an immediate function context - either a consteval function /// or a consteval if function. ImmediateFunctionContext, /// The current expression is potentially evaluated at run time, /// which means that code may be generated to evaluate the value of the /// expression at run time. PotentiallyEvaluated, /// The current expression is potentially evaluated, but any /// declarations referenced inside that expression are only used if /// in fact the current expression is used. /// /// This value is used when parsing default function arguments, for which /// we would like to provide diagnostics (e.g., passing non-POD arguments /// through varargs) but do not want to mark declarations as "referenced" /// until the default argument is used. PotentiallyEvaluatedIfUsed }; using ImmediateInvocationCandidate = llvm::PointerIntPair<ConstantExpr *, 1>; /// Data structure used to record current or nested /// expression evaluation contexts. struct ExpressionEvaluationContextRecord { /// The expression evaluation context. ExpressionEvaluationContext Context; /// Whether the enclosing context needed a cleanup. CleanupInfo ParentCleanup; /// The number of active cleanup objects when we entered /// this expression evaluation context. unsigned NumCleanupObjects; /// The number of typos encountered during this expression evaluation /// context (i.e. the number of TypoExprs created). unsigned NumTypos; MaybeODRUseExprSet SavedMaybeODRUseExprs; /// The lambdas that are present within this context, if it /// is indeed an unevaluated context. SmallVector<LambdaExpr *, 2> Lambdas; /// The declaration that provides context for lambda expressions /// and block literals if the normal declaration context does not /// suffice, e.g., in a default function argument. Decl *ManglingContextDecl; /// If we are processing a decltype type, a set of call expressions /// for which we have deferred checking the completeness of the return type. SmallVector<CallExpr *, 8> DelayedDecltypeCalls; /// If we are processing a decltype type, a set of temporary binding /// expressions for which we have deferred checking the destructor. SmallVector<CXXBindTemporaryExpr *, 8> DelayedDecltypeBinds; llvm::SmallPtrSet<const Expr *, 8> PossibleDerefs; /// Expressions appearing as the LHS of a volatile assignment in this /// context. We produce a warning for these when popping the context if /// they are not discarded-value expressions nor unevaluated operands. SmallVector<Expr*, 2> VolatileAssignmentLHSs; /// Set of candidates for starting an immediate invocation. llvm::SmallVector<ImmediateInvocationCandidate, 4> ImmediateInvocationCandidates; /// Set of DeclRefExprs referencing a consteval function when used in a /// context not already known to be immediately invoked. llvm::SmallPtrSet<DeclRefExpr *, 4> ReferenceToConsteval; /// \brief Describes whether we are in an expression constext which we have /// to handle differently. enum ExpressionKind { EK_Decltype, EK_TemplateArgument, EK_Other } ExprContext; // A context can be nested in both a discarded statement context and // an immediate function context, so they need to be tracked independently. bool InDiscardedStatement; bool InImmediateFunctionContext; ExpressionEvaluationContextRecord(ExpressionEvaluationContext Context, unsigned NumCleanupObjects, CleanupInfo ParentCleanup, Decl *ManglingContextDecl, ExpressionKind ExprContext) : Context(Context), ParentCleanup(ParentCleanup), NumCleanupObjects(NumCleanupObjects), NumTypos(0), ManglingContextDecl(ManglingContextDecl), ExprContext(ExprContext), InDiscardedStatement(false), InImmediateFunctionContext(false) {} bool isUnevaluated() const { return Context == ExpressionEvaluationContext::Unevaluated || Context == ExpressionEvaluationContext::UnevaluatedAbstract || Context == ExpressionEvaluationContext::UnevaluatedList; } bool isConstantEvaluated() const { return Context == ExpressionEvaluationContext::ConstantEvaluated || Context == ExpressionEvaluationContext::ImmediateFunctionContext; } bool isImmediateFunctionContext() const { return Context == ExpressionEvaluationContext::ImmediateFunctionContext || (Context == ExpressionEvaluationContext::DiscardedStatement && InImmediateFunctionContext); } bool isDiscardedStatementContext() const { return Context == ExpressionEvaluationContext::DiscardedStatement || (Context == ExpressionEvaluationContext::ImmediateFunctionContext && InDiscardedStatement); } }; /// A stack of expression evaluation contexts. SmallVector<ExpressionEvaluationContextRecord, 8> ExprEvalContexts; /// Emit a warning for all pending noderef expressions that we recorded. void WarnOnPendingNoDerefs(ExpressionEvaluationContextRecord &Rec); /// Compute the mangling number context for a lambda expression or /// block literal. Also return the extra mangling decl if any. /// /// \param DC - The DeclContext containing the lambda expression or /// block literal. std::tuple<MangleNumberingContext *, Decl *> getCurrentMangleNumberContext(const DeclContext *DC); /// SpecialMemberOverloadResult - The overloading result for a special member /// function. /// /// This is basically a wrapper around PointerIntPair. The lowest bits of the /// integer are used to determine whether overload resolution succeeded. class SpecialMemberOverloadResult { public: enum Kind { NoMemberOrDeleted, Ambiguous, Success }; private: llvm::PointerIntPair<CXXMethodDecl*, 2> Pair; public: SpecialMemberOverloadResult() : Pair() {} SpecialMemberOverloadResult(CXXMethodDecl *MD) : Pair(MD, MD->isDeleted() ? NoMemberOrDeleted : Success) {} CXXMethodDecl *getMethod() const { return Pair.getPointer(); } void setMethod(CXXMethodDecl *MD) { Pair.setPointer(MD); } Kind getKind() const { return static_cast<Kind>(Pair.getInt()); } void setKind(Kind K) { Pair.setInt(K); } }; class SpecialMemberOverloadResultEntry : public llvm::FastFoldingSetNode, public SpecialMemberOverloadResult { public: SpecialMemberOverloadResultEntry(const llvm::FoldingSetNodeID &ID) : FastFoldingSetNode(ID) {} }; /// A cache of special member function overload resolution results /// for C++ records. llvm::FoldingSet<SpecialMemberOverloadResultEntry> SpecialMemberCache; /// A cache of the flags available in enumerations with the flag_bits /// attribute. mutable llvm::DenseMap<const EnumDecl*, llvm::APInt> FlagBitsCache; /// The kind of translation unit we are processing. /// /// When we're processing a complete translation unit, Sema will perform /// end-of-translation-unit semantic tasks (such as creating /// initializers for tentative definitions in C) once parsing has /// completed. Modules and precompiled headers perform different kinds of /// checks. const 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; class GlobalMethodPool { public: using Lists = std::pair<ObjCMethodList, ObjCMethodList>; using iterator = llvm::DenseMap<Selector, Lists>::iterator; iterator begin() { return Methods.begin(); } iterator end() { return Methods.end(); } iterator find(Selector Sel) { return Methods.find(Sel); } std::pair<iterator, bool> insert(std::pair<Selector, Lists> &&Val) { return Methods.insert(Val); } int count(Selector Sel) const { return Methods.count(Sel); } bool empty() const { return Methods.empty(); } private: llvm::DenseMap<Selector, Lists> Methods; }; /// Method Pool - allows efficient lookup when typechecking messages to "id". /// We need to maintain a list, since selectors can have differing signatures /// across classes. In Cocoa, this happens to be extremely uncommon (only 1% /// of selectors are "overloaded"). /// At the head of the list it is recorded whether there were 0, 1, or >= 2 /// methods inside categories with a particular selector. GlobalMethodPool MethodPool; /// Method selectors used in a \@selector expression. Used for implementation /// of -Wselector. llvm::MapVector<Selector, SourceLocation> ReferencedSelectors; /// List of SourceLocations where 'self' is implicitly retained inside a /// block. llvm::SmallVector<std::pair<SourceLocation, const BlockDecl *>, 1> ImplicitlyRetainedSelfLocs; /// Kinds of C++ special members. enum CXXSpecialMember { CXXDefaultConstructor, CXXCopyConstructor, CXXMoveConstructor, CXXCopyAssignment, CXXMoveAssignment, CXXDestructor, CXXInvalid }; typedef llvm::PointerIntPair<CXXRecordDecl *, 3, CXXSpecialMember> SpecialMemberDecl; /// The C++ special members which we are currently in the process of /// declaring. If this process recursively triggers the declaration of the /// same special member, we should act as if it is not yet declared. llvm::SmallPtrSet<SpecialMemberDecl, 4> SpecialMembersBeingDeclared; /// Kinds of defaulted comparison operator functions. enum class DefaultedComparisonKind : unsigned char { /// This is not a defaultable comparison operator. None, /// This is an operator== that should be implemented as a series of /// subobject comparisons. Equal, /// This is an operator<=> that should be implemented as a series of /// subobject comparisons. ThreeWay, /// This is an operator!= that should be implemented as a rewrite in terms /// of a == comparison. NotEqual, /// This is an <, <=, >, or >= that should be implemented as a rewrite in /// terms of a <=> comparison. Relational, }; /// The function definitions which were renamed as part of typo-correction /// to match their respective declarations. We want to keep track of them /// to ensure that we don't emit a "redefinition" error if we encounter a /// correctly named definition after the renamed definition. llvm::SmallPtrSet<const NamedDecl *, 4> TypoCorrectedFunctionDefinitions; /// Stack of types that correspond to the parameter entities that are /// currently being copy-initialized. Can be empty. llvm::SmallVector<QualType, 4> CurrentParameterCopyTypes; void ReadMethodPool(Selector Sel); void updateOutOfDateSelector(Selector Sel); /// Private Helper predicate to check for 'self'. bool isSelfExpr(Expr *RExpr); bool isSelfExpr(Expr *RExpr, const ObjCMethodDecl *Method); /// Cause the active diagnostic on the DiagosticsEngine to be /// emitted. This is closely coupled to the SemaDiagnosticBuilder class and /// should not be used elsewhere. void EmitCurrentDiagnostic(unsigned DiagID); /// Records and restores the CurFPFeatures state on entry/exit of compound /// statements. class FPFeaturesStateRAII { public: FPFeaturesStateRAII(Sema &S) : S(S), OldFPFeaturesState(S.CurFPFeatures) { OldOverrides = S.FpPragmaStack.CurrentValue; } ~FPFeaturesStateRAII() { S.CurFPFeatures = OldFPFeaturesState; S.FpPragmaStack.CurrentValue = OldOverrides; } FPOptionsOverride getOverrides() { return OldOverrides; } private: Sema& S; FPOptions OldFPFeaturesState; FPOptionsOverride OldOverrides; }; void addImplicitTypedef(StringRef Name, QualType T); bool WarnedStackExhausted = false; /// Increment when we find a reference; decrement when we find an ignored /// assignment. Ultimately the value is 0 if every reference is an ignored /// assignment. llvm::DenseMap<const VarDecl *, int> RefsMinusAssignments; Optional<std::unique_ptr<DarwinSDKInfo>> CachedDarwinSDKInfo; 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(); /// This virtual key function only exists to limit the emission of debug info /// describing the Sema class. GCC and Clang only emit debug info for a class /// with a vtable when the vtable is emitted. Sema is final and not /// polymorphic, but the debug info size savings are so significant that it is /// worth adding a vtable just to take advantage of this optimization. virtual void anchor(); const LangOptions &getLangOpts() const { return LangOpts; } OpenCLOptions &getOpenCLOptions() { return OpenCLFeatures; } FPOptions &getCurFPFeatures() { return CurFPFeatures; } DiagnosticsEngine &getDiagnostics() const { return Diags; } SourceManager &getSourceManager() const { return SourceMgr; } Preprocessor &getPreprocessor() const { return PP; } ASTContext &getASTContext() const { return Context; } ASTConsumer &getASTConsumer() const { return Consumer; } ASTMutationListener *getASTMutationListener() const; ExternalSemaSource* getExternalSource() const { return ExternalSource; } DarwinSDKInfo *getDarwinSDKInfoForAvailabilityChecking(SourceLocation Loc, StringRef Platform); ///Registers an external source. If an external source already exists, /// creates a multiplex external source and appends to it. /// ///\param[in] E - A non-null external sema source. /// void addExternalSource(ExternalSemaSource *E); void PrintStats() const; /// Warn that the stack is nearly exhausted. void warnStackExhausted(SourceLocation Loc); /// Run some code with "sufficient" stack space. (Currently, at least 256K is /// guaranteed). Produces a warning if we're low on stack space and allocates /// more in that case. Use this in code that may recurse deeply (for example, /// in template instantiation) to avoid stack overflow. void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref<void()> Fn); /// Helper class that creates diagnostics with optional /// template instantiation stacks. /// /// This class provides a wrapper around the basic DiagnosticBuilder /// class that emits diagnostics. ImmediateDiagBuilder is /// responsible for emitting the diagnostic (as DiagnosticBuilder /// does) and, if the diagnostic comes from inside a template /// instantiation, printing the template instantiation stack as /// well. class ImmediateDiagBuilder : public DiagnosticBuilder { Sema &SemaRef; unsigned DiagID; public: ImmediateDiagBuilder(DiagnosticBuilder &DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} ImmediateDiagBuilder(DiagnosticBuilder &&DB, Sema &SemaRef, unsigned DiagID) : DiagnosticBuilder(DB), SemaRef(SemaRef), DiagID(DiagID) {} // This is a cunning lie. DiagnosticBuilder actually performs move // construction in its copy constructor (but due to varied uses, it's not // possible to conveniently express this as actual move construction). So // the default copy ctor here is fine, because the base class disables the // source anyway, so the user-defined ~ImmediateDiagBuilder is a safe no-op // in that case anwyay. ImmediateDiagBuilder(const ImmediateDiagBuilder &) = default; ~ImmediateDiagBuilder() { // If we aren't active, there is nothing to do. if (!isActive()) return; // Otherwise, we need to emit the diagnostic. First clear the diagnostic // builder itself so it won't emit the diagnostic in its own destructor. // // This seems wasteful, in that as written the DiagnosticBuilder dtor will // do its own needless checks to see if the diagnostic needs to be // emitted. However, because we take care to ensure that the builder // objects never escape, a sufficiently smart compiler will be able to // eliminate that code. Clear(); // Dispatch to Sema to emit the diagnostic. SemaRef.EmitCurrentDiagnostic(DiagID); } /// Teach operator<< to produce an object of the correct type. template <typename T> friend const ImmediateDiagBuilder & operator<<(const ImmediateDiagBuilder &Diag, const T &Value) { const DiagnosticBuilder &BaseDiag = Diag; BaseDiag << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const ImmediateDiagBuilder &operator<<(T &&V) const { const DiagnosticBuilder &BaseDiag = *this; BaseDiag << std::move(V); return *this; } }; /// Bitmask to contain the list of reasons a single diagnostic should be /// emitted, based on its language. This permits multiple offload systems /// to coexist in the same translation unit. enum class DeviceDiagnosticReason { /// Diagnostic doesn't apply to anything. Included for completeness, but /// should make this a no-op. None = 0, /// OpenMP specific diagnostic. OmpDevice = 1 << 0, OmpHost = 1 << 1, OmpAll = OmpDevice | OmpHost, /// CUDA specific diagnostics. CudaDevice = 1 << 2, CudaHost = 1 << 3, CudaAll = CudaDevice | CudaHost, /// SYCL specific diagnostic. Sycl = 1 << 4, /// ESIMD specific diagnostic. Esimd = 1 << 5, /// A flag representing 'all'. This can be used to avoid the check /// all-together and make this behave as it did before the /// DiagnosticReason was added (that is, unconditionally emit). /// Note: This needs to be updated if any flags above are added. All = OmpAll | CudaAll | Sycl | Esimd, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/All) }; private: // A collection of a pair of undefined functions and their callers known // to be reachable from a routine on the device (kernel or device function). typedef std::pair<const FunctionDecl *, const FunctionDecl *> CallPair; llvm::SmallVector<CallPair> UndefinedReachableFromSyclDevice; public: // Helper routine to add a pair of Callee-Caller pair of FunctionDecl * // to UndefinedReachableFromSyclDevice. void addFDToReachableFromSyclDevice(const FunctionDecl *Callee, const FunctionDecl *Caller) { UndefinedReachableFromSyclDevice.push_back(std::make_pair(Callee, Caller)); } // Helper routine to check if a pair of Callee-Caller FunctionDecl * // is in UndefinedReachableFromSyclDevice. bool isFDReachableFromSyclDevice(const FunctionDecl *Callee, const FunctionDecl *Caller) { return llvm::any_of(UndefinedReachableFromSyclDevice, [Callee, Caller](const CallPair &P) { return P.first == Callee && P.second == Caller; }); } /// A generic diagnostic builder for errors which may or may not be deferred. /// /// In CUDA, there exist constructs (e.g. variable-length arrays, try/catch) /// which are not allowed to appear inside __device__ functions and are /// allowed to appear in __host__ __device__ functions only if the host+device /// function is never codegen'ed. /// /// To handle this, we use the notion of "deferred diagnostics", where we /// attach a diagnostic to a FunctionDecl that's emitted iff it's codegen'ed. /// /// This class lets you emit either a regular diagnostic, a deferred /// diagnostic, or no diagnostic at all, according to an argument you pass to /// its constructor, thus simplifying the process of creating these "maybe /// deferred" diagnostics. class SemaDiagnosticBuilder { public: enum Kind { /// Emit no diagnostics. K_Nop, /// Emit the diagnostic immediately (i.e., behave like Sema::Diag()). K_Immediate, /// Emit the diagnostic immediately, and, if it's a warning or error, also /// emit a call stack showing how this function can be reached by an a /// priori known-emitted function. K_ImmediateWithCallStack, /// Create a deferred diagnostic, which is emitted only if the function /// it's attached to is codegen'ed. Also emit a call stack as with /// K_ImmediateWithCallStack. K_Deferred }; SemaDiagnosticBuilder(Kind K, SourceLocation Loc, unsigned DiagID, FunctionDecl *Fn, Sema &S, DeviceDiagnosticReason R); SemaDiagnosticBuilder(SemaDiagnosticBuilder &&D); SemaDiagnosticBuilder(const SemaDiagnosticBuilder &) = default; ~SemaDiagnosticBuilder(); bool isImmediate() const { return ImmediateDiag.hasValue(); } /// Convertible to bool: True if we immediately emitted an error, false if /// we didn't emit an error or we created a deferred error. /// /// Example usage: /// /// if (SemaDiagnosticBuilder(...) << foo << bar) /// return ExprError(); /// /// But see CUDADiagIfDeviceCode() and CUDADiagIfHostCode() -- you probably /// want to use these instead of creating a SemaDiagnosticBuilder yourself. operator bool() const { return isImmediate(); } template <typename T> friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const T &Value) { if (Diag.ImmediateDiag.hasValue()) *Diag.ImmediateDiag << Value; else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId] .getDiag() .second << Value; return Diag; } // It is necessary to limit this to rvalue reference to avoid calling this // function with a bitfield lvalue argument since non-const reference to // bitfield is not allowed. template <typename T, typename = typename std::enable_if< !std::is_lvalue_reference<T>::value>::type> const SemaDiagnosticBuilder &operator<<(T &&V) const { if (ImmediateDiag.hasValue()) *ImmediateDiag << std::move(V); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].getDiag().second << std::move(V); return *this; } friend const SemaDiagnosticBuilder & operator<<(const SemaDiagnosticBuilder &Diag, const PartialDiagnostic &PD) { if (Diag.ImmediateDiag.hasValue()) PD.Emit(*Diag.ImmediateDiag); else if (Diag.PartialDiagId.hasValue()) Diag.S.DeviceDeferredDiags[Diag.Fn][*Diag.PartialDiagId] .getDiag() .second = PD; return Diag; } void AddFixItHint(const FixItHint &Hint) const { if (ImmediateDiag.hasValue()) ImmediateDiag->AddFixItHint(Hint); else if (PartialDiagId.hasValue()) S.DeviceDeferredDiags[Fn][*PartialDiagId].getDiag().second.AddFixItHint( Hint); } friend ExprResult ExprError(const SemaDiagnosticBuilder &) { return ExprError(); } friend StmtResult StmtError(const SemaDiagnosticBuilder &) { return StmtError(); } operator ExprResult() const { return ExprError(); } operator StmtResult() const { return StmtError(); } operator TypeResult() const { return TypeError(); } operator DeclResult() const { return DeclResult(true); } operator MemInitResult() const { return MemInitResult(true); } private: Sema &S; SourceLocation Loc; unsigned DiagID; FunctionDecl *Fn; bool ShowCallStack; // Invariant: At most one of these Optionals has a value. // FIXME: Switch these to a Variant once that exists. llvm::Optional<ImmediateDiagBuilder> ImmediateDiag; llvm::Optional<unsigned> PartialDiagId; }; /// Is the last error level diagnostic immediate. This is used to determined /// whether the next info diagnostic should be immediate. bool IsLastErrorImmediate = true; /// Emit a diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint = false); /// Emit a partial diagnostic. SemaDiagnosticBuilder Diag(SourceLocation Loc, const PartialDiagnostic &PD, bool DeferHint = false); /// Build a partial diagnostic. PartialDiagnostic PDiag(unsigned DiagID = 0); // in SemaInternal.h /// Whether deferrable diagnostics should be deferred. bool DeferDiags = false; /// RAII class to control scope of DeferDiags. class DeferDiagsRAII { Sema &S; bool SavedDeferDiags = false; public: DeferDiagsRAII(Sema &S, bool DeferDiags) : S(S), SavedDeferDiags(S.DeferDiags) { S.DeferDiags = DeferDiags; } ~DeferDiagsRAII() { S.DeferDiags = SavedDeferDiags; } }; /// Whether uncompilable error has occurred. This includes error happens /// in deferred diagnostics. bool hasUncompilableErrorOccurred() const; bool findMacroSpelling(SourceLocation &loc, StringRef name); /// Get a string to suggest for zero-initialization of a type. std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const; std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const; /// Calls \c Lexer::getLocForEndOfToken() SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset = 0); /// Retrieve the module loader associated with the preprocessor. ModuleLoader &getModuleLoader() const; /// Invent a new identifier for parameters of abbreviated templates. IdentifierInfo * InventAbbreviatedTemplateParameterTypeName(IdentifierInfo *ParamName, unsigned Index); void emitAndClearUnusedLocalTypedefWarnings(); private: /// Function or variable declarations to be checked for whether the deferred /// diagnostics should be emitted. llvm::SmallSetVector<Decl *, 4> DeclsToCheckForDeferredDiags; public: // Emit all deferred diagnostics. void emitDeferredDiags(); enum TUFragmentKind { /// The global module fragment, between 'module;' and a module-declaration. Global, /// A normal translation unit fragment. For a non-module unit, this is the /// entire translation unit. Otherwise, it runs from the module-declaration /// to the private-module-fragment (if any) or the end of the TU (if not). Normal, /// The private module fragment, between 'module :private;' and the end of /// the translation unit. Private }; void ActOnStartOfTranslationUnit(); void ActOnEndOfTranslationUnit(); void ActOnEndOfTranslationUnitFragment(TUFragmentKind Kind); void CheckDelegatingCtorCycles(); Scope *getScopeForContext(DeclContext *Ctx); void PushFunctionScope(); void PushBlockScope(Scope *BlockScope, BlockDecl *Block); sema::LambdaScopeInfo *PushLambdaScope(); /// This is used to inform Sema what the current TemplateParameterDepth /// is during Parsing. Currently it is used to pass on the depth /// when parsing generic lambda 'auto' parameters. void RecordParsingTemplateParameterDepth(unsigned Depth); void PushCapturedRegionScope(Scope *RegionScope, CapturedDecl *CD, RecordDecl *RD, CapturedRegionKind K, unsigned OpenMPCaptureLevel = 0); /// Custom deleter to allow FunctionScopeInfos to be kept alive for a short /// time after they've been popped. class PoppedFunctionScopeDeleter { Sema *Self; public: explicit PoppedFunctionScopeDeleter(Sema *Self) : Self(Self) {} void operator()(sema::FunctionScopeInfo *Scope) const; }; using PoppedFunctionScopePtr = std::unique_ptr<sema::FunctionScopeInfo, PoppedFunctionScopeDeleter>; PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP = nullptr, const Decl *D = nullptr, QualType BlockType = QualType()); sema::FunctionScopeInfo *getCurFunction() const { return FunctionScopes.empty() ? nullptr : FunctionScopes.back(); } sema::FunctionScopeInfo *getEnclosingFunction() const; void setFunctionHasBranchIntoScope(); void setFunctionHasBranchProtectedScope(); void setFunctionHasIndirectGoto(); void setFunctionHasMustTail(); void PushCompoundScope(bool IsStmtExpr); void PopCompoundScope(); sema::CompoundScopeInfo &getCurCompoundScope() const; bool hasAnyUnrecoverableErrorsInThisFunction() const; /// Retrieve the current block, if any. sema::BlockScopeInfo *getCurBlock(); /// Get the innermost lambda enclosing the current location, if any. This /// looks through intervening non-lambda scopes such as local functions and /// blocks. sema::LambdaScopeInfo *getEnclosingLambda() const; /// Retrieve the current lambda scope info, if any. /// \param IgnoreNonLambdaCapturingScope true if should find the top-most /// lambda scope info ignoring all inner capturing scopes that are not /// lambda scopes. sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope = false); /// Retrieve the current generic lambda info, if any. sema::LambdaScopeInfo *getCurGenericLambda(); /// Retrieve the current captured region, if any. sema::CapturedRegionScopeInfo *getCurCapturedRegion(); /// Retrieve the current function, if any, that should be analyzed for /// potential availability violations. sema::FunctionScopeInfo *getCurFunctionAvailabilityContext(); /// WeakTopLevelDeclDecls - access to \#pragma weak-generated Decls SmallVectorImpl<Decl *> &WeakTopLevelDecls() { return WeakTopLevelDecl; } /// Called before parsing a function declarator belonging to a function /// declaration. void ActOnStartFunctionDeclarationDeclarator(Declarator &D, unsigned TemplateParameterDepth); /// Called after parsing a function declarator belonging to a function /// declaration. void ActOnFinishFunctionDeclarationDeclarator(Declarator &D); void ActOnComment(SourceRange Comment); //===--------------------------------------------------------------------===// // Type Analysis / Processing: SemaType.cpp. // QualType BuildQualifiedType(QualType T, SourceLocation Loc, Qualifiers Qs, const DeclSpec *DS = nullptr); QualType BuildQualifiedType(QualType T, SourceLocation Loc, unsigned CVRA, const DeclSpec *DS = nullptr); QualType BuildPointerType(QualType T, 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 BuildMatrixType(QualType T, Expr *NumRows, Expr *NumColumns, SourceLocation AttrLoc); QualType BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace, SourceLocation AttrLoc); /// Same as above, but constructs the AddressSpace index if not provided. QualType BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace, SourceLocation AttrLoc); SYCLIntelFPGAIVDepAttr * BuildSYCLIntelFPGAIVDepAttr(const AttributeCommonInfo &CI, Expr *Expr1, Expr *Expr2); LoopUnrollHintAttr *BuildLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); OpenCLUnrollHintAttr * BuildOpenCLLoopUnrollHintAttr(const AttributeCommonInfo &A, Expr *E); SYCLIntelFPGALoopCountAttr * BuildSYCLIntelFPGALoopCountAttr(const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGAInitiationIntervalAttr * BuildSYCLIntelFPGAInitiationIntervalAttr(const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGAMaxConcurrencyAttr * BuildSYCLIntelFPGAMaxConcurrencyAttr(const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGAMaxInterleavingAttr * BuildSYCLIntelFPGAMaxInterleavingAttr(const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGASpeculatedIterationsAttr * BuildSYCLIntelFPGASpeculatedIterationsAttr(const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGALoopCoalesceAttr * BuildSYCLIntelFPGALoopCoalesceAttr(const AttributeCommonInfo &CI, Expr *E); bool CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc); bool CheckFunctionReturnType(QualType T, SourceLocation Loc); /// Build a function type. /// /// This routine checks the function type according to C++ rules and /// under the assumption that the result type and parameter types have /// just been instantiated from a template. It therefore duplicates /// some of the behavior of GetTypeForDeclarator, but in a much /// simpler form that is only suitable for this narrow use case. /// /// \param T The return type of the function. /// /// \param ParamTypes The parameter types of the function. This array /// will be modified to account for adjustments to the types of the /// function parameters. /// /// \param Loc The location of the entity whose type involves this /// function type or, if there is no such entity, the location of the /// type that will have function type. /// /// \param Entity The name of the entity that involves the function /// type, if known. /// /// \param EPI Extra information about the function type. Usually this will /// be taken from an existing function with the same prototype. /// /// \returns A suitable function type, if there are no errors. The /// unqualified type will always be a FunctionProtoType. /// Otherwise, returns a NULL type. QualType BuildFunctionType(QualType T, MutableArrayRef<QualType> ParamTypes, SourceLocation Loc, DeclarationName Entity, const FunctionProtoType::ExtProtoInfo &EPI); QualType BuildMemberPointerType(QualType T, QualType Class, SourceLocation Loc, DeclarationName Entity); QualType BuildBlockPointerType(QualType T, SourceLocation Loc, DeclarationName Entity); QualType BuildParenType(QualType T); QualType BuildAtomicType(QualType T, SourceLocation Loc); QualType BuildReadPipeType(QualType T, SourceLocation Loc); QualType BuildWritePipeType(QualType T, SourceLocation Loc); QualType BuildBitIntType(bool IsUnsigned, Expr *BitWidth, SourceLocation Loc); TypeSourceInfo *GetTypeForDeclarator(Declarator &D, Scope *S); TypeSourceInfo *GetTypeForDeclaratorCast(Declarator &D, QualType FromTy); /// Package the given type and TSI into a ParsedType. ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo); DeclarationNameInfo GetNameForDeclarator(Declarator &D); DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name); static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo = nullptr); CanThrowResult canThrow(const Stmt *E); /// Determine whether the callee of a particular function call can throw. /// E, D and Loc are all optional. static CanThrowResult canCalleeThrow(Sema &S, const Expr *E, const Decl *D, SourceLocation Loc = SourceLocation()); const FunctionProtoType *ResolveExceptionSpec(SourceLocation Loc, const FunctionProtoType *FPT); void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI); bool CheckSpecifiedExceptionType(QualType &T, SourceRange Range); bool CheckDistantExceptionSpec(QualType T); bool CheckEquivalentExceptionSpec(FunctionDecl *Old, FunctionDecl *New); bool CheckEquivalentExceptionSpec( const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool CheckEquivalentExceptionSpec( const PartialDiagnostic &DiagID, const PartialDiagnostic & NoteID, const FunctionProtoType *Old, SourceLocation OldLoc, const FunctionProtoType *New, SourceLocation NewLoc); bool handlerCanCatch(QualType HandlerType, QualType ExceptionType); bool CheckExceptionSpecSubset(const PartialDiagnostic &DiagID, const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const PartialDiagnostic &NoThrowDiagID, const FunctionProtoType *Superset, SourceLocation SuperLoc, const FunctionProtoType *Subset, SourceLocation SubLoc); bool CheckParamExceptionSpec(const PartialDiagnostic &NestedDiagID, const PartialDiagnostic &NoteID, const FunctionProtoType *Target, SourceLocation TargetLoc, const FunctionProtoType *Source, SourceLocation SourceLoc); TypeResult ActOnTypeName(Scope *S, Declarator &D); /// The parser has parsed the context-sensitive type 'instancetype' /// in an Objective-C message declaration. Return the appropriate type. ParsedType ActOnObjCInstanceType(SourceLocation Loc); /// Abstract class used to diagnose incomplete types. struct TypeDiagnoser { TypeDiagnoser() {} virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) = 0; virtual ~TypeDiagnoser() {} }; static int getPrintable(int I) { return I; } static unsigned getPrintable(unsigned I) { return I; } static bool getPrintable(bool B) { return B; } static const char * getPrintable(const char *S) { return S; } static StringRef getPrintable(StringRef S) { return S; } static const std::string &getPrintable(const std::string &S) { return S; } static const IdentifierInfo *getPrintable(const IdentifierInfo *II) { return II; } static DeclarationName getPrintable(DeclarationName N) { return N; } static QualType getPrintable(QualType T) { return T; } static SourceRange getPrintable(SourceRange R) { return R; } static SourceRange getPrintable(SourceLocation L) { return L; } static SourceRange getPrintable(const Expr *E) { return E->getSourceRange(); } static SourceRange getPrintable(TypeLoc TL) { return TL.getSourceRange();} template <typename... Ts> class BoundTypeDiagnoser : public TypeDiagnoser { protected: unsigned DiagID; std::tuple<const Ts &...> Args; template <std::size_t... Is> void emit(const SemaDiagnosticBuilder &DB, std::index_sequence<Is...>) const { // Apply all tuple elements to the builder in order. bool Dummy[] = {false, (DB << getPrintable(std::get<Is>(Args)))...}; (void)Dummy; } public: BoundTypeDiagnoser(unsigned DiagID, const Ts &...Args) : TypeDiagnoser(), DiagID(DiagID), Args(Args...) { assert(DiagID != 0 && "no diagnostic for type diagnoser"); } void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, DiagID); emit(DB, std::index_sequence_for<Ts...>()); DB << T; } }; /// Do a check to make sure \p Name looks like a legal argument for the /// swift_name attribute applied to decl \p D. Raise a diagnostic if the name /// is invalid for the given declaration. /// /// \p AL is used to provide caret diagnostics in case of a malformed name. /// /// \returns true if the name is a valid swift name for \p D, false otherwise. bool DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, const ParsedAttr &AL, bool IsAsync); /// A derivative of BoundTypeDiagnoser for which the diagnostic's type /// parameter is preceded by a 0/1 enum that is 1 if the type is sizeless. /// For example, a diagnostic with no other parameters would generally have /// the form "...%select{incomplete|sizeless}0 type %1...". template <typename... Ts> class SizelessTypeDiagnoser : public BoundTypeDiagnoser<Ts...> { public: SizelessTypeDiagnoser(unsigned DiagID, const Ts &... Args) : BoundTypeDiagnoser<Ts...>(DiagID, Args...) {} void diagnose(Sema &S, SourceLocation Loc, QualType T) override { const SemaDiagnosticBuilder &DB = S.Diag(Loc, this->DiagID); this->emit(DB, std::index_sequence_for<Ts...>()); DB << T->isSizelessType() << T; } }; enum class CompleteTypeKind { /// Apply the normal rules for complete types. In particular, /// treat all sizeless types as incomplete. Normal, /// Relax the normal rules for complete types so that they include /// sizeless built-in types. AcceptSizeless, // FIXME: Eventually we should flip the default to Normal and opt in // to AcceptSizeless rather than opt out of it. Default = AcceptSizeless }; private: /// Methods for marking which expressions involve dereferencing a pointer /// marked with the 'noderef' attribute. Expressions are checked bottom up as /// they are parsed, meaning that a noderef pointer may not be accessed. For /// example, in `&*p` where `p` is a noderef pointer, we will first parse the /// `*p`, but need to check that `address of` is called on it. This requires /// keeping a container of all pending expressions and checking if the address /// of them are eventually taken. void CheckSubscriptAccessOfNoDeref(const ArraySubscriptExpr *E); void CheckAddressOfNoDeref(const Expr *E); void CheckMemberAccessOfNoDeref(const MemberExpr *E); bool RequireCompleteTypeImpl(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser *Diagnoser); struct ModuleScope { SourceLocation BeginLoc; clang::Module *Module = nullptr; bool ModuleInterface = false; bool ImplicitGlobalModuleFragment = false; VisibleModuleSet OuterVisibleModules; }; /// The modules we're currently parsing. llvm::SmallVector<ModuleScope, 16> ModuleScopes; /// Namespace definitions that we will export when they finish. llvm::SmallPtrSet<const NamespaceDecl*, 8> DeferredExportedNamespaces; /// Get the module whose scope we are currently within. Module *getCurrentModule() const { return ModuleScopes.empty() ? nullptr : ModuleScopes.back().Module; } /// Helper function to judge if we are in module purview. /// Return false if we are not in a module. bool isCurrentModulePurview() const { return getCurrentModule() ? getCurrentModule()->isModulePurview() : false; } /// Enter the scope of the global module. Module *PushGlobalModuleFragment(SourceLocation BeginLoc, bool IsImplicit); /// Leave the scope of the global module. void PopGlobalModuleFragment(); VisibleModuleSet VisibleModules; public: /// Get the module owning an entity. Module *getOwningModule(const Decl *Entity) { return Entity->getOwningModule(); } /// Make a merged definition of an existing hidden definition \p ND /// visible at the specified location. void makeMergedDefinitionVisible(NamedDecl *ND); bool isModuleVisible(const Module *M, bool ModulePrivate = false); // When loading a non-modular PCH files, this is used to restore module // visibility. void makeModuleVisible(Module *Mod, SourceLocation ImportLoc) { VisibleModules.setVisible(Mod, ImportLoc); } /// Determine whether a declaration is visible to name lookup. bool isVisible(const NamedDecl *D) { return D->isUnconditionallyVisible() || isVisibleSlow(D); } /// Determine whether any declaration of an entity is visible. bool hasVisibleDeclaration(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr) { return isVisible(D) || hasVisibleDeclarationSlow(D, Modules); } bool hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules); bool hasVisibleMergedDefinition(NamedDecl *Def); bool hasMergedDefinitionInCurrentModule(NamedDecl *Def); /// Determine if \p D and \p Suggested have a structurally compatible /// layout as described in C11 6.2.7/1. bool hasStructuralCompatLayout(Decl *D, Decl *Suggested); /// Determine if \p D has a visible definition. If not, suggest a declaration /// that should be made visible to expose the definition. bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete = false); bool hasVisibleDefinition(const NamedDecl *D) { NamedDecl *Hidden; return hasVisibleDefinition(const_cast<NamedDecl*>(D), &Hidden); } /// Determine if the template parameter \p D has a visible default argument. bool hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is an explicit /// specialization declaration for a specialization of a template. (For a /// member specialization, use hasVisibleMemberSpecialization.) bool hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if there is a visible declaration of \p D that is a member /// specialization declaration (as opposed to an instantiated declaration). bool hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules = nullptr); /// Determine if \p A and \p B are equivalent internal linkage declarations /// from different modules, and thus an ambiguity error can be downgraded to /// an extension warning. bool isEquivalentInternalLinkageDeclaration(const NamedDecl *A, const NamedDecl *B); void diagnoseEquivalentInternalLinkageDeclarations( SourceLocation Loc, const NamedDecl *D, ArrayRef<const NamedDecl *> Equiv); bool isUsualDeallocationFunction(const CXXMethodDecl *FD); bool isCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind = CompleteTypeKind::Default) { return !RequireCompleteTypeImpl(Loc, T, Kind, nullptr); } bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, unsigned DiagID); bool RequireCompleteType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, Diagnoser); } bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID) { return RequireCompleteType(Loc, T, CompleteTypeKind::Default, DiagID); } template <typename... Ts> bool RequireCompleteType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteType(Loc, T, CompleteTypeKind::Normal, Diagnoser); } /// Get the type of expression E, triggering instantiation to complete the /// type if necessary -- that is, if the expression refers to a templated /// static data member of incomplete array type. /// /// May still return an incomplete type if instantiation was not possible or /// if the type is incomplete for a different reason. Use /// RequireCompleteExprType instead if a diagnostic is expected for an /// incomplete expression type. QualType getCompletedType(Expr *E); void completeExprArrayBound(Expr *E); bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser); bool RequireCompleteExprType(Expr *E, unsigned DiagID); template <typename... Ts> bool RequireCompleteExprType(Expr *E, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser); } template <typename... Ts> bool RequireCompleteSizedExprType(Expr *E, unsigned DiagID, const Ts &... Args) { SizelessTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireCompleteExprType(E, CompleteTypeKind::Normal, Diagnoser); } bool RequireLiteralType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID); template <typename... Ts> bool RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireLiteralType(Loc, T, Diagnoser); } QualType getElaboratedType(ElaboratedTypeKeyword Keyword, const CXXScopeSpec &SS, QualType T, TagDecl *OwnedTagDecl = nullptr); // Returns the underlying type of a decltype with the given expression. QualType getDecltypeForExpr(Expr *E); QualType BuildTypeofExprType(Expr *E); /// 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, bool AsUnevaluated = true); QualType BuildUnaryTransformType(QualType BaseType, UnaryTransformType::UTTKind UKind, SourceLocation Loc); //===--------------------------------------------------------------------===// // Symbol table / Decl tracking callbacks: SemaDecl.cpp. // struct SkipBodyInfo { SkipBodyInfo() : ShouldSkip(false), CheckSameAsPrevious(false), Previous(nullptr), New(nullptr) {} bool ShouldSkip; bool CheckSameAsPrevious; NamedDecl *Previous; NamedDecl *New; }; DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType = nullptr); void DiagnoseUseOfUnimplementedSelectors(); bool isSimpleTypeSpecifier(tok::TokenKind Kind) const; ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS = nullptr, bool isClassName = false, bool HasTrailingDot = false, ParsedType ObjectType = nullptr, bool IsCtorOrDtorName = false, bool WantNontrivialTypeSourceInfo = false, bool IsClassTemplateDeductionContext = true, IdentifierInfo **CorrectedII = nullptr); TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S); bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S); void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName = false); /// Attempt to behave like MSVC in situations where lookup of an unqualified /// type name has failed in a dependent context. In these situations, we /// automatically form a DependentTypeName that will retry lookup in a related /// scope during instantiation. ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg); /// Describes the result of the name lookup and resolution performed /// by \c ClassifyName(). enum NameClassificationKind { /// This name is not a type or template in this context, but might be /// something else. NC_Unknown, /// Classification failed; an error has been produced. NC_Error, /// The name has been typo-corrected to a keyword. NC_Keyword, /// The name was classified as a type. NC_Type, /// The name was classified as a specific non-type, non-template /// declaration. ActOnNameClassifiedAsNonType should be called to /// convert the declaration to an expression. NC_NonType, /// The name was classified as an ADL-only function name. /// ActOnNameClassifiedAsUndeclaredNonType should be called to convert the /// result to an expression. NC_UndeclaredNonType, /// The name denotes a member of a dependent type that could not be /// resolved. ActOnNameClassifiedAsDependentNonType should be called to /// convert the result to an expression. NC_DependentNonType, /// The name was classified as an overload set, and an expression /// representing that overload set has been formed. /// ActOnNameClassifiedAsOverloadSet should be called to form a suitable /// expression referencing the overload set. NC_OverloadSet, /// The name was classified as a template whose specializations are types. NC_TypeTemplate, /// The name was classified as a variable template name. NC_VarTemplate, /// The name was classified as a function template name. NC_FunctionTemplate, /// The name was classified as an ADL-only function template name. NC_UndeclaredTemplate, /// The name was classified as a concept name. NC_Concept, }; class NameClassification { NameClassificationKind Kind; union { ExprResult Expr; NamedDecl *NonTypeDecl; TemplateName Template; ParsedType Type; }; explicit NameClassification(NameClassificationKind Kind) : Kind(Kind) {} public: NameClassification(ParsedType Type) : Kind(NC_Type), Type(Type) {} NameClassification(const IdentifierInfo *Keyword) : Kind(NC_Keyword) {} static NameClassification Error() { return NameClassification(NC_Error); } static NameClassification Unknown() { return NameClassification(NC_Unknown); } static NameClassification OverloadSet(ExprResult E) { NameClassification Result(NC_OverloadSet); Result.Expr = E; return Result; } static NameClassification NonType(NamedDecl *D) { NameClassification Result(NC_NonType); Result.NonTypeDecl = D; return Result; } static NameClassification UndeclaredNonType() { return NameClassification(NC_UndeclaredNonType); } static NameClassification DependentNonType() { return NameClassification(NC_DependentNonType); } static NameClassification TypeTemplate(TemplateName Name) { NameClassification Result(NC_TypeTemplate); Result.Template = Name; return Result; } static NameClassification VarTemplate(TemplateName Name) { NameClassification Result(NC_VarTemplate); Result.Template = Name; return Result; } static NameClassification FunctionTemplate(TemplateName Name) { NameClassification Result(NC_FunctionTemplate); Result.Template = Name; return Result; } static NameClassification Concept(TemplateName Name) { NameClassification Result(NC_Concept); Result.Template = Name; return Result; } static NameClassification UndeclaredTemplate(TemplateName Name) { NameClassification Result(NC_UndeclaredTemplate); Result.Template = Name; return Result; } NameClassificationKind getKind() const { return Kind; } ExprResult getExpression() const { assert(Kind == NC_OverloadSet); return Expr; } ParsedType getType() const { assert(Kind == NC_Type); return Type; } NamedDecl *getNonTypeDecl() const { assert(Kind == NC_NonType); return NonTypeDecl; } TemplateName getTemplateName() const { assert(Kind == NC_TypeTemplate || Kind == NC_FunctionTemplate || Kind == NC_VarTemplate || Kind == NC_Concept || Kind == NC_UndeclaredTemplate); return Template; } TemplateNameKind getTemplateNameKind() const { switch (Kind) { case NC_TypeTemplate: return TNK_Type_template; case NC_FunctionTemplate: return TNK_Function_template; case NC_VarTemplate: return TNK_Var_template; case NC_Concept: return TNK_Concept_template; case NC_UndeclaredTemplate: return TNK_Undeclared_template; default: llvm_unreachable("unsupported name classification."); } } }; /// Perform name lookup on the given name, classifying it based on /// the results of name lookup and the following token. /// /// This routine is used by the parser to resolve identifiers and help direct /// parsing. When the identifier cannot be found, this routine will attempt /// to correct the typo and classify based on the resulting name. /// /// \param S The scope in which we're performing name lookup. /// /// \param SS The nested-name-specifier that precedes the name. /// /// \param Name The identifier. If typo correction finds an alternative name, /// this pointer parameter will be updated accordingly. /// /// \param NameLoc The location of the identifier. /// /// \param NextToken The token following the identifier. Used to help /// disambiguate the name. /// /// \param CCC The correction callback, if typo correction is desired. NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC = nullptr); /// Act on the result of classifying a name as an undeclared (ADL-only) /// non-type declaration. ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc); /// Act on the result of classifying a name as an undeclared member of a /// dependent base class. ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand); /// Act on the result of classifying a name as a specific non-type /// declaration. ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken); /// Act on the result of classifying a name as an overload set. ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet); /// Describes the detailed kind of a template name. Used in diagnostics. enum class TemplateNameKindForDiagnostics { ClassTemplate, FunctionTemplate, VarTemplate, AliasTemplate, TemplateTemplateParam, Concept, DependentTemplate }; TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name); /// Determine whether it's plausible that E was intended to be a /// template-name. bool mightBeIntendedToBeTemplateName(ExprResult E, bool &Dependent) { if (!getLangOpts().CPlusPlus || E.isInvalid()) return false; Dependent = false; if (auto *DRE = dyn_cast<DeclRefExpr>(E.get())) return !DRE->hasExplicitTemplateArgs(); if (auto *ME = dyn_cast<MemberExpr>(E.get())) return !ME->hasExplicitTemplateArgs(); Dependent = true; if (auto *DSDRE = dyn_cast<DependentScopeDeclRefExpr>(E.get())) return !DSDRE->hasExplicitTemplateArgs(); if (auto *DSME = dyn_cast<CXXDependentScopeMemberExpr>(E.get())) return !DSME->hasExplicitTemplateArgs(); // Any additional cases recognized here should also be handled by // diagnoseExprIntendedAsTemplateName. return false; } void diagnoseExprIntendedAsTemplateName(Scope *S, ExprResult TemplateName, SourceLocation Less, SourceLocation Greater); void warnOnReservedIdentifier(const NamedDecl *D); Decl *ActOnDeclarator(Scope *S, Declarator &D); NamedDecl *HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists); bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID); 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); NamedDecl *getShadowedDeclaration(const BindingDecl *D, const LookupResult &R); void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R); void CheckShadow(Scope *S, VarDecl *D); /// Warn if 'E', which is an expression that is about to be modified, refers /// to a shadowing declaration. void CheckShadowingDeclModification(Expr *E, SourceLocation Loc); void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI); private: /// Map of current shadowing declarations to shadowed declarations. Warn if /// it looks like the user is trying to modify the shadowing declaration. llvm::DenseMap<const NamedDecl *, const NamedDecl *> ShadowingDecls; public: void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange); void handleTagNumbering(const TagDecl *Tag, Scope *TagScope); void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD); void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D); NamedDecl* ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous); NamedDecl* ActOnTypedefNameDecl(Scope* S, DeclContext* DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration); NamedDecl *ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef<BindingDecl *> Bindings = None); NamedDecl * ActOnDecompositionDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists); // Returns true if the variable declaration is a redeclaration bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous); void CheckVariableDeclarationType(VarDecl *NewVD); bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init); void CheckCompleteVariableDeclaration(VarDecl *VD); void CheckCompleteDecompositionDeclaration(DecompositionDecl *DD); void MaybeSuggestAddingStaticToDecl(const FunctionDecl *D); NamedDecl* ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope); bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD); enum class CheckConstexprKind { /// Diagnose issues that are non-constant or that are extensions. Diagnose, /// Identify whether this function satisfies the formal rules for constexpr /// functions in the current lanugage mode (with no extensions). CheckValid }; bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind); void DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD); void FindHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); void NoteHiddenVirtualMethods(CXXMethodDecl *MD, SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods); // Returns true if the function declaration is a redeclaration bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization); bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl); bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT); void CheckMain(FunctionDecl *FD, const DeclSpec &D); void CheckMSVCRTEntryPoint(FunctionDecl *FD); Attr *getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition); void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D); 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); ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); void SetParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc); // Contexts where using non-trivial C union types can be disallowed. This is // passed to err_non_trivial_c_union_in_invalid_context. enum NonTrivialCUnionContext { // Function parameter. NTCUC_FunctionParam, // Function return. NTCUC_FunctionReturn, // Default-initialized object. NTCUC_DefaultInitializedObject, // Variable with automatic storage duration. NTCUC_AutoVar, // Initializer expression that might copy from another object. NTCUC_CopyInit, // Assignment. NTCUC_Assignment, // Compound literal. NTCUC_CompoundLiteral, // Block capture. NTCUC_BlockCapture, // lvalue-to-rvalue conversion of volatile type. NTCUC_LValueToRValueVolatile, }; /// Emit diagnostics if the initializer or any of its explicit or /// implicitly-generated subexpressions require copying or /// default-initializing a type that is or contains a C union type that is /// non-trivial to copy or default-initialize. void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc); // These flags are passed to checkNonTrivialCUnion. enum NonTrivialCUnionKind { NTCUK_Init = 0x1, NTCUK_Destruct = 0x2, NTCUK_Copy = 0x4, }; /// Emit diagnostics if a non-trivial C union type or a struct that contains /// a non-trivial C union is used in an invalid context. void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind); void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit); 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 ActOnStartTrailingRequiresClause(Scope *S, Declarator &D); ExprResult ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr); ExprResult ActOnRequiresClause(ExprResult ConstraintExpr); void ActOnStartOfObjCMethodDef(Scope *S, Decl *D); bool isObjCMethodDecl(Decl *D) { return D && isa<ObjCMethodDecl>(D); } /// Determine whether we can delay parsing the body of a function or /// function template until it is used, assuming we don't care about emitting /// code for that function. /// /// This will be \c false if we may need the body of the function in the /// middle of parsing an expression (where it's impractical to switch to /// parsing a different function), for instance, if it's constexpr in C++11 /// or has an 'auto' return type in C++14. These cases are essentially bugs. bool canDelayFunctionBody(const Declarator &D); /// Determine whether we can skip parsing the body of a function /// definition, assuming we don't care about analyzing its body or emitting /// code for that function. /// /// This will be \c false only if we may need the body of the function in /// order to parse the rest of the program (for instance, if it is /// \c constexpr in C++11 or has an 'auto' return type in C++14). bool canSkipFunctionBody(Decl *D); void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body); Decl *ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation); Decl *ActOnSkippedFunctionBody(Decl *Decl); void ActOnFinishInlineFunctionDef(FunctionDecl *D); /// ActOnFinishDelayedAttribute - Invoked when we have finished parsing an /// attribute for which parsing is delayed. void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs); /// Diagnose any unused parameters in the given sequence of /// ParmVarDecl pointers. void DiagnoseUnusedParameters(ArrayRef<ParmVarDecl *> Parameters); /// Diagnose whether the size of parameters or return value of a /// function or obj-c method definition is pass-by-value and larger than a /// specified threshold. void DiagnoseSizeOfParametersAndReturnValue(ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D); void DiagnoseInvalidJumps(Stmt *Body); Decl *ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc); /// Handle a C++11 empty-declaration and attribute-declaration. Decl *ActOnEmptyDeclaration(Scope *S, const ParsedAttributesView &AttrList, SourceLocation SemiLoc); enum class ModuleDeclKind { Interface, ///< 'export module X;' Implementation, ///< 'module X;' }; /// The parser has processed a module-declaration that begins the definition /// of a module interface or implementation. DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl); /// The parser has processed a global-module-fragment declaration that begins /// the definition of the global module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc); /// The parser has processed a private-module-fragment declaration that begins /// the definition of the private module fragment of the current module unit. /// \param ModuleLoc The location of the 'module' keyword. /// \param PrivateLoc The location of the 'private' keyword. DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc); /// The parser has processed a module import declaration. /// /// \param StartLoc The location of the first token in the declaration. This /// could be the location of an '@', 'export', or 'import'. /// \param ExportLoc The location of the 'export' keyword, if any. /// \param ImportLoc The location of the 'import' keyword. /// \param Path The module access path. DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path); DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, Module *M, ModuleIdPath Path = {}); /// The parser has processed a module import translated from a /// #include or similar preprocessing directive. void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod); void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod); /// The parsed has entered a submodule. void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod); /// The parser has left a submodule. void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod); /// Create an implicit import of the given module at the given /// source location, for error recovery, if possible. /// /// This routine is typically used when an entity found by name lookup /// is actually hidden within a module that we know about but the user /// has forgotten to import. void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod); /// Kinds of missing import. Note, the values of these enumerators correspond /// to %select values in diagnostics. enum class MissingImportKind { Declaration, Definition, DefaultArgument, ExplicitSpecialization, PartialSpecialization }; /// Diagnose that the specified declaration needs to be visible but /// isn't, and suggest a module import that would resolve the problem. void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover = true); void diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover); Decl *ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc); Decl *ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc); /// We've found a use of a templated declaration that would trigger an /// implicit instantiation. Check that any relevant explicit specializations /// and partial specializations are visible, and diagnose if not. void checkSpecializationVisibility(SourceLocation Loc, NamedDecl *Spec); /// Retrieve a suitable printing policy for diagnostics. PrintingPolicy getPrintingPolicy() const { return getPrintingPolicy(Context, PP); } /// Retrieve a suitable printing policy for diagnostics. static PrintingPolicy getPrintingPolicy(const ASTContext &Ctx, const Preprocessor &PP); /// Scope actions. void ActOnPopScope(SourceLocation Loc, Scope *S); void ActOnTranslationUnitScope(Scope *S); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord); Decl *ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, MultiTemplateParamsArg TemplateParams, bool IsExplicitInstantiation, RecordDecl *&AnonRecord); Decl *BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy); Decl *BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record); /// Common ways to introduce type names without a tag for use in diagnostics. /// Keep in sync with err_tag_reference_non_tag. enum NonTagKind { NTK_NonStruct, NTK_NonClass, NTK_NonUnion, NTK_NonEnum, NTK_Typedef, NTK_TypeAlias, NTK_Template, NTK_TypeAliasTemplate, NTK_TemplateTemplateArgument, }; /// Given a non-tag type declaration, returns an enum useful for indicating /// what kind of non-tag type this is. NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK); bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name); enum TagUseKind { TUK_Reference, // Reference to a tag: 'struct foo *X;' TUK_Declaration, // Fwd decl of a tag: 'struct foo;' TUK_Definition, // Definition of a tag: 'struct foo { int X; } Y;' TUK_Friend // Friend declaration: 'friend struct foo;' }; Decl *ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody = nullptr); 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); /// For a defaulted function, the kind of defaulted function that it is. class DefaultedFunctionKind { CXXSpecialMember SpecialMember : 8; DefaultedComparisonKind Comparison : 8; public: DefaultedFunctionKind() : SpecialMember(CXXInvalid), Comparison(DefaultedComparisonKind::None) { } DefaultedFunctionKind(CXXSpecialMember CSM) : SpecialMember(CSM), Comparison(DefaultedComparisonKind::None) {} DefaultedFunctionKind(DefaultedComparisonKind Comp) : SpecialMember(CXXInvalid), Comparison(Comp) {} bool isSpecialMember() const { return SpecialMember != CXXInvalid; } bool isComparison() const { return Comparison != DefaultedComparisonKind::None; } explicit operator bool() const { return isSpecialMember() || isComparison(); } CXXSpecialMember asSpecialMember() const { return SpecialMember; } DefaultedComparisonKind asComparison() const { return Comparison; } /// Get the index of this function kind for use in diagnostics. unsigned getDiagnosticIndex() const { static_assert(CXXInvalid > CXXDestructor, "invalid should have highest index"); static_assert((unsigned)DefaultedComparisonKind::None == 0, "none should be equal to zero"); return SpecialMember + (unsigned)Comparison; } }; DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD); CXXSpecialMember getSpecialMember(const CXXMethodDecl *MD) { return getDefaultedFunctionKind(MD).asSpecialMember(); } DefaultedComparisonKind getDefaultedComparisonKind(const FunctionDecl *FD) { return getDefaultedFunctionKind(FD).asComparison(); } void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl<Decl *> &AllIvarDecls); Decl *ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility); // This is used for both record definitions and ObjC interface declarations. void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef<Decl *> Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); /// ActOnTagStartDefinition - Invoked when we have entered the /// scope of a tag's definition (e.g., for an enumeration, class, /// struct, or union). void ActOnTagStartDefinition(Scope *S, Decl *TagDecl); /// Perform ODR-like check for C/ObjC when merging tag types from modules. /// Differently from C++, actually parse the body and reject / error out /// in case of a structural mismatch. bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody); typedef void *SkippedDefinitionContext; /// Invoked when we enter a tag definition that we're skipping. SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD); Decl *ActOnObjCContainerStartDefinition(Decl *IDecl); /// ActOnStartCXXMemberDeclarations - Invoked when we have parsed a /// C++ record definition's base-specifiers clause and are starting its /// member declarations. void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc); /// ActOnTagFinishDefinition - Invoked once we have finished parsing /// the definition of a tag (enumeration, class, struct, or union). void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange); void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context); void ActOnObjCContainerFinishDefinition(); /// Invoked when we must temporarily exit the objective-c container /// scope for parsing/looking-up C constructs. /// /// Must be followed by a call to \see ActOnObjCReenterContainerContext void ActOnObjCTemporaryExitContainerContext(DeclContext *DC); void ActOnObjCReenterContainerContext(DeclContext *DC); /// ActOnTagDefinitionError - Invoked when there was an unrecoverable /// error parsing the definition of a tag. void ActOnTagDefinitionError(Scope *S, Decl *TagDecl); EnumConstantDecl *CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val); bool CheckEnumUnderlyingType(TypeSourceInfo *TI); bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev); /// Determine whether the body of an anonymous enumeration should be skipped. /// \param II The name of the first enumerator. SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc); Decl *ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val); void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef<Decl *> Elements, Scope *S, const ParsedAttributesView &Attr); /// Set the current declaration context until it gets popped. void PushDeclContext(Scope *S, DeclContext *DC); void PopDeclContext(); /// EnterDeclaratorContext - Used when we must lookup names in the context /// of a declarator's nested name specifier. void EnterDeclaratorContext(Scope *S, DeclContext *DC); void ExitDeclaratorContext(Scope *S); /// Enter a template parameter scope, after it's been associated with a particular /// DeclContext. Causes lookup within the scope to chain through enclosing contexts /// in the correct order. void EnterTemplatedContext(Scope *S, DeclContext *DC); /// Push the parameters of D, which must be a function, into scope. void ActOnReenterFunctionContext(Scope* S, Decl* D); void ActOnExitFunctionContext(); DeclContext *getFunctionLevelDeclContext(); /// getCurFunctionDecl - If inside of a function body, this returns a pointer /// to the function decl for the function being parsed. If we're currently /// in a 'block', this returns the containing context. FunctionDecl *getCurFunctionDecl(); /// getCurMethodDecl - If inside of a method body, this returns a pointer to /// the method decl for the method being parsed. If we're currently /// in a 'block', this returns the containing context. ObjCMethodDecl *getCurMethodDecl(); /// getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method /// or C function we're in, otherwise return null. If we're currently /// in a 'block', this returns the containing context. NamedDecl *getCurFunctionOrMethodDecl(); /// Add this decl to the scope shadowed decl chains. void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext = true); /// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true /// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns /// true if 'D' belongs to the given declaration context. /// /// \param AllowInlineNamespace If \c true, allow the declaration to be in the /// enclosing namespace set of the context, rather than contained /// directly within it. bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S = nullptr, bool AllowInlineNamespace = false); /// Finds the scope corresponding to the given decl context, if it /// happens to be an enclosing scope. Otherwise return NULL. static Scope *getScopeForDeclContext(Scope *S, DeclContext *DC); /// Subroutines of ActOnDeclarator(). TypedefDecl *ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo); bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New); /// Describes the kind of merge to perform for availability /// attributes (including "deprecated", "unavailable", and "availability"). enum AvailabilityMergeKind { /// Don't merge availability attributes at all. AMK_None, /// Merge availability attributes for a redeclaration, which requires /// an exact match. AMK_Redeclaration, /// Merge availability attributes for an override, which requires /// an exact match or a weakening of constraints. AMK_Override, /// Merge availability attributes for an implementation of /// a protocol requirement. AMK_ProtocolImplementation, /// Merge availability attributes for an implementation of /// an optional protocol requirement. AMK_OptionalProtocolImplementation }; /// Describes the kind of priority given to an availability attribute. /// /// The sum of priorities deteremines the final priority of the attribute. /// The final priority determines how the attribute will be merged. /// An attribute with a lower priority will always remove higher priority /// attributes for the specified platform when it is being applied. An /// attribute with a higher priority will not be applied if the declaration /// already has an availability attribute with a lower priority for the /// specified platform. The final prirority values are not expected to match /// the values in this enumeration, but instead should be treated as a plain /// integer value. This enumeration just names the priority weights that are /// used to calculate that final vaue. enum AvailabilityPriority : int { /// The availability attribute was specified explicitly next to the /// declaration. AP_Explicit = 0, /// The availability attribute was applied using '#pragma clang attribute'. AP_PragmaClangAttribute = 1, /// The availability attribute for a specific platform was inferred from /// an availability attribute for another platform. AP_InferredFromOtherPlatform = 2 }; /// Attribute merging methods. Return true if a new attribute was added. AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority); TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis); VisibilityAttr *mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis); UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl); DLLImportAttr *mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI); DLLExportAttr *mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI); MSInheritanceAttr *mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model); ErrorAttr *mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic); FormatAttr *mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg); SectionAttr *mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); CodeSegAttr *mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name); AlwaysInlineAttr *mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident); MinSizeAttr *mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI); SwiftNameAttr *mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name); OptimizeNoneAttr *mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL); InternalLinkageAttr *mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL); WebAssemblyImportNameAttr *mergeImportNameAttr( Decl *D, const WebAssemblyImportNameAttr &AL); WebAssemblyImportModuleAttr *mergeImportModuleAttr( Decl *D, const WebAssemblyImportModuleAttr &AL); EnforceTCBAttr *mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL); EnforceTCBLeafAttr *mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL); BTFDeclTagAttr *mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &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, bool ConsiderRequiresClauses = true); enum class AllowedExplicit { /// Allow no explicit functions to be used. None, /// Allow explicit conversion functions but not explicit constructors. Conversions, /// Allow both explicit conversion functions and explicit constructors. All }; ImplicitConversionSequence TryImplicitConversion(Expr *From, QualType ToType, bool SuppressUserConversions, AllowedExplicit AllowExplicit, bool InOverloadResolution, bool CStyle, bool AllowObjCWritebackConversion); bool IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType); bool IsFloatingPointPromotion(QualType FromType, QualType ToType); bool IsComplexPromotion(QualType FromType, QualType ToType); bool IsPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType, bool &IncompatibleObjC); bool isObjCWritebackConversion(QualType FromType, QualType ToType, QualType &ConvertedType); bool IsBlockPointerConversion(QualType FromType, QualType ToType, QualType& ConvertedType); bool FunctionParamTypesAreEqual(const FunctionProtoType *OldType, const FunctionProtoType *NewType, unsigned *ArgPos = nullptr); void HandleFunctionTypeMismatch(PartialDiagnostic &PDiag, QualType FromType, QualType ToType); void maybeExtendBlockObject(ExprResult &E); CastKind PrepareCastToObjCObjectPointer(ExprResult &E); bool CheckPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath& BasePath, bool IgnoreBaseAccess, bool Diagnose = true); bool IsMemberPointerConversion(Expr *From, QualType FromType, QualType ToType, bool InOverloadResolution, QualType &ConvertedType); bool CheckMemberPointerConversion(Expr *From, QualType ToType, CastKind &Kind, CXXCastPath &BasePath, bool IgnoreBaseAccess); bool IsQualificationConversion(QualType FromType, QualType ToType, bool CStyle, bool &ObjCLifetimeConversion); bool IsFunctionConversion(QualType FromType, QualType ToType, QualType &ResultTy); bool DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType); bool isSameOrCompatibleFunctionType(QualType Param, QualType Arg); bool CanPerformAggregateInitializationForOverloadResolution( const InitializedEntity &Entity, InitListExpr *From); bool IsStringInit(Expr *Init, const ArrayType *AT); bool CanPerformCopyInitialization(const InitializedEntity &Entity, ExprResult Init); ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList = false, bool AllowExplicit = false); ExprResult PerformObjectArgumentInitialization(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, CXXMethodDecl *Method); /// Check that the lifetime of the initializer (and its subobjects) is /// sufficient for initializing the entity, and perform lifetime extension /// (when permitted) if not. void checkInitializerLifetime(const InitializedEntity &Entity, Expr *Init); ExprResult PerformContextuallyConvertToBool(Expr *From); ExprResult PerformContextuallyConvertToObjCPointer(Expr *From); /// Contexts in which a converted constant expression is required. enum CCEKind { CCEK_CaseValue, ///< Expression in a case label. CCEK_Enumerator, ///< Enumerator value with fixed underlying type. CCEK_TemplateArg, ///< Value of a non-type template parameter. CCEK_ArrayBound, ///< Array bound in array declarator or new-expression. CCEK_ExplicitBool, ///< Condition in an explicit(bool) specifier. CCEK_Noexcept ///< Condition in a noexcept(bool) specifier. }; ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, llvm::APSInt &Value, CCEKind CCE); ExprResult CheckConvertedConstantExpression(Expr *From, QualType T, APValue &Value, CCEKind CCE, NamedDecl *Dest = nullptr); /// Abstract base class used to perform a contextual implicit /// conversion from an expression to any type passing a filter. class ContextualImplicitConverter { public: bool Suppress; bool SuppressConversion; ContextualImplicitConverter(bool Suppress = false, bool SuppressConversion = false) : Suppress(Suppress), SuppressConversion(SuppressConversion) {} /// Determine whether the specified type is a valid destination type /// for this conversion. virtual bool match(QualType T) = 0; /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the expression has incomplete class type. virtual SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a diagnostic when the only matching conversion function /// is explicit. virtual SemaDiagnosticBuilder diagnoseExplicitConv( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; /// Emits a note for the explicit conversion function. virtual SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when there are multiple possible conversion /// functions. virtual SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) = 0; /// Emits a note for one of the candidate conversions. virtual SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) = 0; /// Emits a diagnostic when we picked a conversion function /// (for cases when we are not allowed to pick a conversion function). virtual SemaDiagnosticBuilder diagnoseConversion( Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) = 0; virtual ~ContextualImplicitConverter() {} }; class ICEConvertDiagnoser : public ContextualImplicitConverter { bool AllowScopedEnumerations; public: ICEConvertDiagnoser(bool AllowScopedEnumerations, bool Suppress, bool SuppressConversion) : ContextualImplicitConverter(Suppress, SuppressConversion), AllowScopedEnumerations(AllowScopedEnumerations) {} /// Match an integral or (possibly scoped) enumeration type. bool match(QualType T) override; SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override { return diagnoseNotInt(S, Loc, T); } /// Emits a diagnostic complaining that the expression does not have /// integral or enumeration type. virtual SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, QualType T) = 0; }; /// Perform a contextual implicit conversion. ExprResult PerformContextualImplicitConversion( SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter); enum ObjCSubscriptKind { OS_Array, OS_Dictionary, OS_Error }; ObjCSubscriptKind CheckSubscriptingKind(Expr *FromE); // Note that LK_String is intentionally after the other literals, as // this is used for diagnostics logic. enum ObjCLiteralKind { LK_Array, LK_Dictionary, LK_Numeric, LK_Boxed, LK_String, LK_Block, LK_None }; ObjCLiteralKind CheckLiteralKind(Expr *FromE); ExprResult PerformObjectMemberConversion(Expr *From, NestedNameSpecifier *Qualifier, NamedDecl *FoundDecl, NamedDecl *Member); // Members have to be NamespaceDecl* or TranslationUnitDecl*. // TODO: make this is a typesafe union. typedef llvm::SmallSetVector<DeclContext *, 16> AssociatedNamespaceSet; typedef llvm::SmallSetVector<CXXRecordDecl *, 16> AssociatedClassSet; using ADLCallKind = CallExpr::ADLCallKind; void AddOverloadCandidate(FunctionDecl *Function, DeclAccessPair FoundDecl, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, bool AllowExplicitConversion = false, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddFunctionCandidates(const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, bool SuppressUserConversions = false, bool PartialOverloading = false, bool FirstArgumentIsBase = false); void AddMethodCandidate(DeclAccessPair FoundDecl, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversion = false, OverloadCandidateParamOrder PO = {}); void AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, ConversionSequenceList EarlyConversions = None, OverloadCandidateParamOrder PO = {}); void AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ObjectType, Expr::Classification ObjectClassification, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, OverloadCandidateParamOrder PO = {}); void AddTemplateOverloadCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool SuppressUserConversions = false, bool PartialOverloading = false, bool AllowExplicit = true, ADLCallKind IsADLCandidate = ADLCallKind::NotADL, OverloadCandidateParamOrder PO = {}); bool CheckNonDependentConversions( FunctionTemplateDecl *FunctionTemplate, ArrayRef<QualType> ParamTypes, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, ConversionSequenceList &Conversions, bool SuppressUserConversions, CXXRecordDecl *ActingContext = nullptr, QualType ObjectType = QualType(), Expr::Classification ObjectClassification = {}, OverloadCandidateParamOrder PO = {}); void AddConversionCandidate( CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddTemplateConversionCandidate( FunctionTemplateDecl *FunctionTemplate, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, Expr *From, QualType ToType, OverloadCandidateSet &CandidateSet, bool AllowObjCConversionOnExplicit, bool AllowExplicit, bool AllowResultConversion = true); void AddSurrogateCandidate(CXXConversionDecl *Conversion, DeclAccessPair FoundDecl, CXXRecordDecl *ActingContext, const FunctionProtoType *Proto, Expr *Object, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddNonMemberOperatorCandidates( const UnresolvedSetImpl &Functions, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); void AddMemberOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, OverloadCandidateParamOrder PO = {}); void AddBuiltinCandidate(QualType *ParamTys, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet, bool IsAssignmentOperator = false, unsigned NumContextualBoolArguments = 0); void AddBuiltinOperatorCandidates(OverloadedOperatorKind Op, SourceLocation OpLoc, ArrayRef<Expr *> Args, OverloadCandidateSet& CandidateSet); void AddArgumentDependentLookupCandidates(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, TemplateArgumentListInfo *ExplicitTemplateArgs, OverloadCandidateSet& CandidateSet, bool PartialOverloading = false); // Emit as a 'note' the specific overload candidate void NoteOverloadCandidate( NamedDecl *Found, FunctionDecl *Fn, OverloadCandidateRewriteKind RewriteKind = OverloadCandidateRewriteKind(), QualType DestType = QualType(), bool TakingAddress = false); // Emit as a series of 'note's all template and non-templates identified by // the expression Expr void NoteAllOverloadCandidates(Expr *E, QualType DestType = QualType(), bool TakingAddress = false); /// Check the enable_if expressions on the given function. Returns the first /// failing attribute, or NULL if they were all successful. EnableIfAttr *CheckEnableIf(FunctionDecl *Function, SourceLocation CallLoc, ArrayRef<Expr *> Args, bool MissingImplicitThis = false); /// Find the failed Boolean condition within a given Boolean /// constant expression, and describe it with a string. std::pair<Expr *, std::string> findFailedBooleanCondition(Expr *Cond); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// non-ArgDependent DiagnoseIfAttrs. /// /// Argument-dependent diagnose_if attributes should be checked each time a /// function is used as a direct callee of a function call. /// /// Returns true if any errors were emitted. bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef<const Expr *> Args, SourceLocation Loc); /// Emit diagnostics for the diagnose_if attributes on Function, ignoring any /// ArgDependent DiagnoseIfAttrs. /// /// Argument-independent diagnose_if attributes should be checked on every use /// of a function. /// /// Returns true if any errors were emitted. bool diagnoseArgIndependentDiagnoseIfAttrs(const NamedDecl *ND, SourceLocation Loc); /// Returns whether the given function's address can be taken or not, /// optionally emitting a diagnostic if the address can't be taken. /// /// Returns false if taking the address of the function is illegal. bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain = false, SourceLocation Loc = SourceLocation()); // [PossiblyAFunctionType] --> [Return] // NonFunctionType --> NonFunctionType // R (A) --> R(A) // R (*)(A) --> R (A) // R (&)(A) --> R (A) // R (S::*)(A) --> R (A) QualType ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType); FunctionDecl * ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType, bool Complain, DeclAccessPair &Found, bool *pHadMultipleCandidates = nullptr); FunctionDecl * resolveAddressOfSingleOverloadCandidate(Expr *E, DeclAccessPair &FoundResult); bool resolveAndFixAddressOfSingleOverloadCandidate( ExprResult &SrcExpr, bool DoFunctionPointerConversion = false); FunctionDecl * ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl, bool Complain = false, DeclAccessPair *Found = nullptr); bool ResolveAndFixSingleFunctionTemplateSpecialization( ExprResult &SrcExpr, bool DoFunctionPointerConverion = false, bool Complain = false, SourceRange OpRangeForComplaining = SourceRange(), QualType DestTypeForComplaining = QualType(), unsigned DiagIDForComplaining = 0); Expr *FixOverloadedFunctionReference(Expr *E, DeclAccessPair FoundDecl, FunctionDecl *Fn); ExprResult FixOverloadedFunctionReference(ExprResult, DeclAccessPair FoundDecl, FunctionDecl *Fn); void AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet, bool PartialOverloading = false); void AddOverloadedCallCandidates( LookupResult &R, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, OverloadCandidateSet &CandidateSet); // An enum used to represent the different possible results of building a // range-based for loop. enum ForRangeStatus { FRS_Success, FRS_NoViableFunction, FRS_DiagnosticIssued }; ForRangeStatus BuildForRangeBeginEndCall(SourceLocation Loc, SourceLocation RangeLoc, const DeclarationNameInfo &NameInfo, LookupResult &MemberLookup, OverloadCandidateSet *CandidateSet, Expr *Range, ExprResult *CallExpr); ExprResult BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig, bool AllowTypoCorrection=true, bool CalleesAddressIsTaken=false); bool buildOverloadedCallSet(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE, MultiExprArg Args, SourceLocation RParenLoc, OverloadCandidateSet *CandidateSet, ExprResult *Result); ExprResult CreateUnresolvedLookupExpr(CXXRecordDecl *NamingClass, NestedNameSpecifierLoc NNSLoc, DeclarationNameInfo DNI, const UnresolvedSetImpl &Fns, bool PerformADL = true); ExprResult CreateOverloadedUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *input, bool RequiresADL = true); void LookupOverloadedBinOp(OverloadCandidateSet &CandidateSet, OverloadedOperatorKind Op, const UnresolvedSetImpl &Fns, ArrayRef<Expr *> Args, bool RequiresADL = true); ExprResult CreateOverloadedBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, bool RequiresADL = true, bool AllowRewrittenCandidates = true, FunctionDecl *DefaultedFn = nullptr); ExprResult BuildSynthesizedThreeWayComparison(SourceLocation OpLoc, const UnresolvedSetImpl &Fns, Expr *LHS, Expr *RHS, FunctionDecl *DefaultedFn); ExprResult CreateOverloadedArraySubscriptExpr(SourceLocation LLoc, SourceLocation RLoc, Expr *Base,Expr *Idx); ExprResult BuildCallToMemberFunction(Scope *S, Expr *MemExpr, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); ExprResult BuildCallToObjectOfClassType(Scope *S, Expr *Object, SourceLocation LParenLoc, MultiExprArg Args, SourceLocation RParenLoc); ExprResult BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc, bool *NoArrowOperatorFound = nullptr); /// CheckCallReturnType - Checks that a call expression's return type is /// complete. Returns true on failure. The location passed in is the location /// that best represents the call. bool CheckCallReturnType(QualType ReturnType, SourceLocation Loc, CallExpr *CE, FunctionDecl *FD); /// Helpers for dealing with blocks and functions. bool CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters, bool CheckParameterNames); void CheckCXXDefaultArguments(FunctionDecl *FD); void CheckExtraCXXDefaultArguments(Declarator &D); Scope *getNonFieldDeclScope(Scope *S); /// \name Name lookup /// /// These routines provide name lookup that is used during semantic /// analysis to resolve the various kinds of names (identifiers, /// overloaded operator names, constructor names, etc.) into zero or /// more declarations within a particular scope. The major entry /// points are LookupName, which performs unqualified name lookup, /// and LookupQualifiedName, which performs qualified name lookup. /// /// All name lookup is performed based on some specific criteria, /// which specify what names will be visible to name lookup and how /// far name lookup should work. These criteria are important both /// for capturing language semantics (certain lookups will ignore /// certain names, for example) and for performance, since name /// lookup is often a bottleneck in the compilation of C++. Name /// lookup criteria is specified via the LookupCriteria enumeration. /// /// The results of name lookup can vary based on the kind of name /// lookup performed, the current language, and the translation /// unit. In C, for example, name lookup will either return nothing /// (no entity found) or a single declaration. In C++, name lookup /// can additionally refer to a set of overloaded functions or /// result in an ambiguity. All of the possible results of name /// lookup are captured by the LookupResult class, which provides /// the ability to distinguish among them. //@{ /// Describes the kind of name lookup to perform. enum LookupNameKind { /// Ordinary name lookup, which finds ordinary names (functions, /// variables, typedefs, etc.) in C and most kinds of names /// (functions, variables, members, types, etc.) in C++. LookupOrdinaryName = 0, /// Tag name lookup, which finds the names of enums, classes, /// structs, and unions. LookupTagName, /// Label name lookup. LookupLabel, /// Member name lookup, which finds the names of /// class/struct/union members. LookupMemberName, /// Look up of an operator name (e.g., operator+) for use with /// operator overloading. This lookup is similar to ordinary name /// lookup, but will ignore any declarations that are class members. LookupOperatorName, /// Look up a name following ~ in a destructor name. This is an ordinary /// lookup, but prefers tags to typedefs. LookupDestructorName, /// Look up of a name that precedes the '::' scope resolution /// operator in C++. This lookup completely ignores operator, object, /// function, and enumerator names (C++ [basic.lookup.qual]p1). LookupNestedNameSpecifierName, /// Look up a namespace name within a C++ using directive or /// namespace alias definition, ignoring non-namespace names (C++ /// [basic.lookup.udir]p1). LookupNamespaceName, /// Look up all declarations in a scope with the given name, /// including resolved using declarations. This is appropriate /// for checking redeclarations for a using declaration. LookupUsingDeclName, /// Look up an ordinary name that is going to be redeclared as a /// name with linkage. This lookup ignores any declarations that /// are outside of the current scope unless they have linkage. See /// C99 6.2.2p4-5 and C++ [basic.link]p6. LookupRedeclarationWithLinkage, /// Look up a friend of a local class. This lookup does not look /// outside the innermost non-class scope. See C++11 [class.friend]p11. LookupLocalFriendName, /// Look up the name of an Objective-C protocol. LookupObjCProtocolName, /// Look up implicit 'self' parameter of an objective-c method. LookupObjCImplicitSelfParam, /// Look up the name of an OpenMP user-defined reduction operation. LookupOMPReductionName, /// Look up the name of an OpenMP user-defined mapper. LookupOMPMapperName, /// Look up any declaration with any name. LookupAnyName }; /// Specifies whether (or how) name lookup is being performed for a /// redeclaration (vs. a reference). enum RedeclarationKind { /// The lookup is a reference to this name that is not for the /// purpose of redeclaring the name. NotForRedeclaration = 0, /// The lookup results will be used for redeclaration of a name, /// if an entity by that name already exists and is visible. ForVisibleRedeclaration, /// The lookup results will be used for redeclaration of a name /// with external linkage; non-visible lookup results with external linkage /// may also be found. ForExternalRedeclaration }; RedeclarationKind forRedeclarationInCurContext() { // A declaration with an owning module for linkage can never link against // anything that is not visible. We don't need to check linkage here; if // the context has internal linkage, redeclaration lookup won't find things // from other TUs, and we can't safely compute linkage yet in general. if (cast<Decl>(CurContext) ->getOwningModuleForLinkage(/*IgnoreLinkage*/true)) return ForVisibleRedeclaration; return ForExternalRedeclaration; } /// The possible outcomes of name lookup for a literal operator. enum LiteralOperatorLookupResult { /// The lookup resulted in an error. LOLR_Error, /// The lookup found no match but no diagnostic was issued. LOLR_ErrorNoDiagnostic, /// The lookup found a single 'cooked' literal operator, which /// expects a normal literal to be built and passed to it. LOLR_Cooked, /// The lookup found a single 'raw' literal operator, which expects /// a string literal containing the spelling of the literal token. LOLR_Raw, /// The lookup found an overload set of literal operator templates, /// which expect the characters of the spelling of the literal token to be /// passed as a non-type template argument pack. LOLR_Template, /// The lookup found an overload set of literal operator templates, /// which expect the character type and characters of the spelling of the /// string literal token to be passed as template arguments. LOLR_StringTemplatePack, }; SpecialMemberOverloadResult LookupSpecialMember(CXXRecordDecl *D, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis); typedef std::function<void(const TypoCorrection &)> TypoDiagnosticGenerator; typedef std::function<ExprResult(Sema &, TypoExpr *, TypoCorrection)> TypoRecoveryCallback; private: bool CppLookupName(LookupResult &R, Scope *S); struct TypoExprState { std::unique_ptr<TypoCorrectionConsumer> Consumer; TypoDiagnosticGenerator DiagHandler; TypoRecoveryCallback RecoveryHandler; TypoExprState(); TypoExprState(TypoExprState &&other) noexcept; TypoExprState &operator=(TypoExprState &&other) noexcept; }; /// The set of unhandled TypoExprs and their associated state. llvm::MapVector<TypoExpr *, TypoExprState> DelayedTypos; /// Creates a new TypoExpr AST node. TypoExpr *createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, SourceLocation TypoLoc); // The set of known/encountered (unique, canonicalized) NamespaceDecls. // // The boolean value will be true to indicate that the namespace was loaded // from an AST/PCH file, or false otherwise. llvm::MapVector<NamespaceDecl*, bool> KnownNamespaces; /// Whether we have already loaded known namespaces from an extenal /// source. bool LoadedExternalKnownNamespaces; /// Helper for CorrectTypo and CorrectTypoDelayed used to create and /// populate a new TypoCorrectionConsumer. Returns nullptr if typo correction /// should be skipped entirely. std::unique_ptr<TypoCorrectionConsumer> makeTypoCorrectionConsumer(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery); public: const TypoExprState &getTypoExprState(TypoExpr *TE) const; /// Clears the state of the given TypoExpr. void clearDelayedTypo(TypoExpr *TE); /// Look up a name, looking for a single declaration. Return /// null if the results were absent, ambiguous, or overloaded. /// /// It is preferable to use the elaborated form and explicitly handle /// ambiguity and overloaded. NamedDecl *LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl = NotForRedeclaration); bool LookupBuiltin(LookupResult &R); void LookupNecessaryTypesForBuiltin(Scope *S, unsigned ID); bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup = false); bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS); bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation = false, bool EnteringContext = false); ObjCProtocolDecl *LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl = NotForRedeclaration); bool LookupInSuper(LookupResult &R, CXXRecordDecl *Class); void LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, UnresolvedSetImpl &Functions); LabelDecl *LookupOrCreateLabel(IdentifierInfo *II, SourceLocation IdentLoc, SourceLocation GnuLabelLoc = SourceLocation()); DeclContextLookupResult LookupConstructors(CXXRecordDecl *Class); CXXConstructorDecl *LookupDefaultConstructor(CXXRecordDecl *Class); CXXConstructorDecl *LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXConstructorDecl *LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals); CXXMethodDecl *LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals); CXXDestructorDecl *LookupDestructor(CXXRecordDecl *Class); bool checkLiteralOperatorId(const CXXScopeSpec &SS, const UnqualifiedId &Id, bool IsUDSuffix); LiteralOperatorLookupResult LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing, StringLiteral *StringLit = nullptr); bool isKnownName(StringRef name); /// Status of the function emission on the CUDA/HIP/OpenMP host/device attrs. enum class FunctionEmissionStatus { Emitted, CUDADiscarded, // Discarded due to CUDA/HIP hostness OMPDiscarded, // Discarded due to OpenMP hostness TemplateDiscarded, // Discarded due to uninstantiated templates Unknown, }; FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final = false); DeviceDiagnosticReason getEmissionReason(const FunctionDecl *Decl); // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check. bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee); void ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Functions); void LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool LoadExternal = true); void LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope = true, bool IncludeDependentBases = false, bool LoadExternal = true); enum CorrectTypoKind { CTK_NonError, // CorrectTypo used in a non error recovery situation. CTK_ErrorRecovery // CorrectTypo used in normal error recovery. }; TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr, bool RecordFailure = true); TypoExpr *CorrectTypoDelayed(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext = nullptr, bool EnteringContext = false, const ObjCObjectPointerType *OPT = nullptr); /// Process any TypoExprs in the given Expr and its children, /// generating diagnostics as appropriate and returning a new Expr if there /// were typos that were all successfully corrected and ExprError if one or /// more typos could not be corrected. /// /// \param E The Expr to check for TypoExprs. /// /// \param InitDecl A VarDecl to avoid because the Expr being corrected is its /// initializer. /// /// \param RecoverUncorrectedTypos If true, when typo correction fails, it /// will rebuild the given Expr with all TypoExprs degraded to RecoveryExprs. /// /// \param Filter A function applied to a newly rebuilt Expr to determine if /// it is an acceptable/usable result from a single combination of typo /// corrections. As long as the filter returns ExprError, different /// combinations of corrections will be tried until all are exhausted. ExprResult CorrectDelayedTyposInExpr( Expr *E, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }); ExprResult CorrectDelayedTyposInExpr( ExprResult ER, VarDecl *InitDecl = nullptr, bool RecoverUncorrectedTypos = false, llvm::function_ref<ExprResult(Expr *)> Filter = [](Expr *E) -> ExprResult { return E; }) { return ER.isInvalid() ? ER : CorrectDelayedTyposInExpr(ER.get(), InitDecl, RecoverUncorrectedTypos, Filter); } void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery = true); void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery = true); void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F); void FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses); void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace); bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old); void DiagnoseAmbiguousLookup(LookupResult &Result); //@} /// Attempts to produce a RecoveryExpr after some AST node cannot be created. ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef<Expr *> SubExprs, QualType T = QualType()); ObjCInterfaceDecl *getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection = false); FunctionDecl *CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc); NamedDecl *LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc); NamedDecl *ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S); void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction( FunctionDecl *FD); void AddKnownFunctionAttributes(FunctionDecl *FD); // More parsing and symbol table subroutines. void ProcessPragmaWeak(Scope *S, Decl *D); // Decl attributes - this routine is the top level dispatcher. void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD); // Helper for delayed processing of attributes. void ProcessDeclAttributeDelayed(Decl *D, const ParsedAttributesView &AttrList); void ProcessDeclAttributeList(Scope *S, Decl *D, const ParsedAttributesView &AL, bool IncludeCXX11Attributes = true); bool ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList); void checkUnusedDeclAttributes(Declarator &D); /// Handles semantic checking for features that are common to all attributes, /// such as checking whether a parameter was properly specified, or the /// correct number of arguments were passed, etc. Returns true if the /// attribute has been diagnosed. bool checkCommonAttributeFeatures(const Decl *D, const ParsedAttr &A); bool checkCommonAttributeFeatures(const Stmt *S, const ParsedAttr &A); /// 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); llvm::Error isValidSectionSpecifier(StringRef Str); bool checkSectionName(SourceLocation LiteralLoc, StringRef Str); bool checkTargetAttr(SourceLocation LiteralLoc, StringRef Str); bool checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, const StringLiteral *Literal, bool &HasDefault, bool &HasCommas, SmallVectorImpl<StringRef> &Strings); bool checkMSInheritanceAttrOnDefinition( CXXRecordDecl *RD, SourceRange Range, bool BestCase, MSInheritanceModel SemanticSpelling); void CheckAlignasUnderalignment(Decl *D); /// Adjust the calling convention of a method to be the ABI default if it /// wasn't specified explicitly. This handles method types formed from /// function type typedefs and typename template arguments. void adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor, SourceLocation Loc); // Check if there is an explicit attribute, but only look through parens. // The intent is to look for an attribute on the current declarator, but not // one that came from a typedef. bool hasExplicitCallingConv(QualType T); /// Get the outermost AttributedType node that sets a calling convention. /// Valid types should not have multiple attributes with different CCs. const AttributedType *getCallingConvAttributedType(QualType T) const; /// Process the attributes before creating an attributed statement. Returns /// the semantic attributes that have been processed. void ProcessStmtAttributes(Stmt *Stmt, const ParsedAttributesWithRange &InAttrs, SmallVectorImpl<const Attr *> &OutAttrs); void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl); /// WarnExactTypedMethods - This routine issues a warning if method /// implementation declaration matches exactly that of its declaration. void WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl); typedef llvm::SmallPtrSet<Selector, 8> SelectorSet; /// CheckImplementationIvars - This routine checks if the instance variables /// listed in the implelementation match those listed in the interface. void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc); /// ImplMethodsVsClassMethods - This is main routine to warn if any method /// remains unimplemented in the class or category \@implementation. void ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool IncompleteImpl = false); /// DiagnoseUnimplementedProperties - This routine warns on those properties /// which must be implemented by this implementation. void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties); /// Diagnose any null-resettable synthesized setters. void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl); /// DefaultSynthesizeProperties - This routine default synthesizes all /// properties which must be synthesized in the class's \@implementation. void DefaultSynthesizeProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl, SourceLocation AtEnd); void DefaultSynthesizeProperties(Scope *S, Decl *D, SourceLocation AtEnd); /// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is /// an ivar synthesized for 'Method' and 'Method' is a property accessor /// declared in class 'IFace'. bool IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, ObjCMethodDecl *Method, ObjCIvarDecl *IV); /// DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which /// backs the property is not used in the property's accessor. void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD); /// GetIvarBackingPropertyAccessor - If method is a property setter/getter and /// it property has a backing ivar, returns this ivar; otherwise, returns NULL. /// It also returns ivar's property on success. ObjCIvarDecl *GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const; /// Called by ActOnProperty to handle \@property declarations in /// class extensions. ObjCPropertyDecl *HandlePropertyInClassExtension(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, unsigned &Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind); /// Called by ActOnProperty and HandlePropertyInClassExtension to /// handle creating the ObjcPropertyDecl for a category or \@interface. ObjCPropertyDecl *CreatePropertyDecl(Scope *S, ObjCContainerDecl *CDecl, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, Selector GetterSel, SourceLocation GetterNameLoc, Selector SetterSel, SourceLocation SetterNameLoc, const bool isReadWrite, const unsigned Attributes, const unsigned AttributesAsWritten, QualType T, TypeSourceInfo *TSI, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); /// AtomicPropertySetterGetterRules - This routine enforces the rule (via /// warning) when atomic property has one but not the other user-declared /// setter or getter. void AtomicPropertySetterGetterRules(ObjCImplDecl* IMPDecl, ObjCInterfaceDecl* IDecl); void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D); void DiagnoseMissingDesignatedInitOverrides( const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD); void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID); enum MethodMatchStrategy { MMS_loose, MMS_strict }; /// MatchTwoMethodDeclarations - Checks if two methods' type match and returns /// true, or false, accordingly. bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy = MMS_strict); /// MatchAllMethodDeclarations - Check methods declaraed in interface or /// or protocol against those declared in their implementations. void MatchAllMethodDeclarations(const SelectorSet &InsMap, const SelectorSet &ClsMap, SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl* IMPDecl, ObjCContainerDecl* IDecl, bool &IncompleteImpl, bool ImmediateClass, bool WarnCategoryMethodImpl=false); /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in /// category matches with those implemented in its primary class and /// warns each time an exact match is found. void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP); /// Add the given method to the list of globally-known methods. void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method); /// Returns default addr space for method qualifiers. LangAS getDefaultCXXMethodAddrSpace() const; private: /// AddMethodToGlobalPool - Add an instance or factory method to the global /// pool. See descriptoin of AddInstanceMethodToGlobalPool. void AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl, bool instance); /// LookupMethodInGlobalPool - Returns the instance or factory method and /// optionally warns if there are multiple signatures. ObjCMethodDecl *LookupMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass, bool instance); public: /// - Returns instance or factory methods in global method pool for /// given selector. It checks the desired kind first, if none is found, and /// parameter checkTheOther is set, it then checks the other kind. If no such /// method or only one method is found, function returns false; otherwise, it /// returns true. bool CollectMultipleMethodsInGlobalPool(Selector Sel, SmallVectorImpl<ObjCMethodDecl*>& Methods, bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound = nullptr); bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl*>& Methods); void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass); private: /// - Returns a selector which best matches given argument list or /// nullptr if none could be found ObjCMethodDecl *SelectBestMethod(Selector Sel, MultiExprArg Args, bool IsInstance, SmallVectorImpl<ObjCMethodDecl*>& Methods); /// Record the typo correction failure and return an empty correction. TypoCorrection FailedCorrection(IdentifierInfo *Typo, SourceLocation TypoLoc, bool RecordFailure = true) { if (RecordFailure) TypoCorrectionFailures[Typo].insert(TypoLoc); return TypoCorrection(); } public: /// AddInstanceMethodToGlobalPool - All instance methods in a translation /// unit are added to a global pool. This allows us to efficiently associate /// a selector with a method declaraation for purposes of typechecking /// messages sent to "id" (where the class of the object is unknown). void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/true); } /// AddFactoryMethodToGlobalPool - Same as above, but for factory methods. void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false) { AddMethodToGlobalPool(Method, impl, /*instance*/false); } /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global /// pool. void AddAnyMethodToGlobalPool(Decl *D); /// LookupInstanceMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupInstanceMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/true); } /// LookupFactoryMethodInGlobalPool - Returns the method and warns if /// there are multiple signatures. ObjCMethodDecl *LookupFactoryMethodInGlobalPool(Selector Sel, SourceRange R, bool receiverIdOrClass=false) { return LookupMethodInGlobalPool(Sel, R, receiverIdOrClass, /*instance*/false); } const ObjCMethodDecl *SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType()); /// LookupImplementedMethodInGlobalPool - Returns the method which has an /// implementation. ObjCMethodDecl *LookupImplementedMethodInGlobalPool(Selector Sel); /// CollectIvarsToConstructOrDestruct - Collect those ivars which require /// initialization. void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl<ObjCIvarDecl*> &Ivars); //===--------------------------------------------------------------------===// // Statement Parsing Callbacks: SemaStmt.cpp. public: class FullExprArg { public: FullExprArg() : E(nullptr) { } FullExprArg(Sema &actions) : E(nullptr) { } ExprResult release() { return E; } Expr *get() const { return E; } Expr *operator->() { return E; } private: // FIXME: No need to make the entire Sema class a friend when it's just // Sema::MakeFullExpr that needs access to the constructor below. friend class Sema; explicit FullExprArg(Expr *expr) : E(expr) {} Expr *E; }; FullExprArg MakeFullExpr(Expr *Arg) { return MakeFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation()); } FullExprArg MakeFullExpr(Expr *Arg, SourceLocation CC) { return FullExprArg( ActOnFinishFullExpr(Arg, CC, /*DiscardedValue*/ false).get()); } FullExprArg MakeFullDiscardedValueExpr(Expr *Arg) { ExprResult FE = ActOnFinishFullExpr(Arg, Arg ? Arg->getExprLoc() : SourceLocation(), /*DiscardedValue*/ true); return FullExprArg(FE.get()); } StmtResult ActOnExprStmt(ExprResult Arg, bool DiscardedValue = true); StmtResult ActOnExprStmtError(); StmtResult ActOnNullStmt(SourceLocation SemiLoc, bool HasLeadingEmptyMacro = false); void ActOnStartOfCompoundStmt(bool IsStmtExpr); void ActOnAfterCompoundStatementLeadingPragmas(); void ActOnFinishOfCompoundStmt(); StmtResult ActOnCompoundStmt(SourceLocation L, SourceLocation R, ArrayRef<Stmt *> Elts, bool isStmtExpr); /// 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 BuildAttributedStmt(SourceLocation AttrsLoc, ArrayRef<const Attr *> Attrs, Stmt *SubStmt); StmtResult ActOnAttributedStmt(const ParsedAttributesWithRange &AttrList, Stmt *SubStmt); bool CheckRebuiltAttributedStmtAttributes(ArrayRef<const Attr *> Attrs); class ConditionResult; StmtResult ActOnIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult BuildIfStmt(SourceLocation IfLoc, IfStatementKind StatementKind, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc, Stmt *ThenVal, SourceLocation ElseLoc, Stmt *ElseVal); StmtResult ActOnStartOfSwitchStmt(SourceLocation SwitchLoc, SourceLocation LParenLoc, Stmt *InitStmt, ConditionResult Cond, SourceLocation RParenLoc); StmtResult ActOnFinishSwitchStmt(SourceLocation SwitchLoc, Stmt *Switch, Stmt *Body); StmtResult ActOnWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc, ConditionResult Cond, SourceLocation RParenLoc, Stmt *Body); StmtResult ActOnDoStmt(SourceLocation DoLoc, Stmt *Body, SourceLocation WhileLoc, SourceLocation CondLParen, Expr *Cond, SourceLocation CondRParen); StmtResult ActOnForStmt(SourceLocation ForLoc, SourceLocation LParenLoc, Stmt *First, ConditionResult Second, FullExprArg Third, SourceLocation RParenLoc, Stmt *Body); ExprResult CheckObjCForCollectionOperand(SourceLocation forLoc, Expr *collection); StmtResult ActOnObjCForCollectionStmt(SourceLocation ForColLoc, Stmt *First, Expr *collection, SourceLocation RParenLoc); StmtResult FinishObjCForCollectionStmt(Stmt *ForCollection, Stmt *Body); enum BuildForRangeKind { /// Initial building of a for-range statement. BFRK_Build, /// Instantiation or recovery rebuild of a for-range statement. Don't /// attempt any typo-correction. BFRK_Rebuild, /// Determining whether a for-range statement could be built. Avoid any /// unnecessary or irreversible actions. BFRK_Check }; StmtResult ActOnCXXForRangeStmt(Scope *S, SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, Stmt *LoopVar, SourceLocation ColonLoc, Expr *Collection, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult BuildCXXForRangeStmt(SourceLocation ForLoc, SourceLocation CoawaitLoc, Stmt *InitStmt, SourceLocation ColonLoc, Stmt *RangeDecl, Stmt *Begin, Stmt *End, Expr *Cond, Expr *Inc, Stmt *LoopVarDecl, SourceLocation RParenLoc, BuildForRangeKind Kind); StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body); StmtResult ActOnGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc, LabelDecl *TheDecl); StmtResult ActOnIndirectGotoStmt(SourceLocation GotoLoc, SourceLocation StarLoc, Expr *DestExp); StmtResult ActOnContinueStmt(SourceLocation ContinueLoc, Scope *CurScope); StmtResult ActOnBreakStmt(SourceLocation BreakLoc, Scope *CurScope); void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, unsigned NumParams); typedef std::pair<StringRef, QualType> CapturedParamNameType; void ActOnCapturedRegionStart(SourceLocation Loc, Scope *CurScope, CapturedRegionKind Kind, ArrayRef<CapturedParamNameType> Params, unsigned OpenMPCaptureLevel = 0); StmtResult ActOnCapturedRegionEnd(Stmt *S); void ActOnCapturedRegionError(); RecordDecl *CreateCapturedStmtRecordDecl(CapturedDecl *&CD, SourceLocation Loc, unsigned NumParams); struct NamedReturnInfo { const VarDecl *Candidate; enum Status : uint8_t { None, MoveEligible, MoveEligibleAndCopyElidable }; Status S; bool isMoveEligible() const { return S != None; }; bool isCopyElidable() const { return S == MoveEligibleAndCopyElidable; } }; enum class SimplerImplicitMoveMode { ForceOff, Normal, ForceOn }; NamedReturnInfo getNamedReturnInfo( Expr *&E, SimplerImplicitMoveMode Mode = SimplerImplicitMoveMode::Normal); NamedReturnInfo getNamedReturnInfo(const VarDecl *VD); const VarDecl *getCopyElisionCandidate(NamedReturnInfo &Info, QualType ReturnType); ExprResult PerformMoveOrCopyInitialization(const InitializedEntity &Entity, const NamedReturnInfo &NRInfo, Expr *Value, bool SupressSimplerImplicitMoves = false); StmtResult ActOnReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, Scope *CurScope); StmtResult BuildReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp); StmtResult ActOnCapScopeReturnStmt(SourceLocation ReturnLoc, Expr *RetValExp, NamedReturnInfo &NRInfo, bool SupressSimplerImplicitMoves); StmtResult ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple, bool IsVolatile, unsigned NumOutputs, unsigned NumInputs, IdentifierInfo **Names, MultiExprArg Constraints, MultiExprArg Exprs, Expr *AsmString, MultiExprArg Clobbers, unsigned NumLabels, SourceLocation RParenLoc); void FillInlineAsmIdentifierInfo(Expr *Res, llvm::InlineAsmIdentifierInfo &Info); ExprResult LookupInlineAsmIdentifier(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool IsUnevaluatedContext); bool LookupInlineAsmField(StringRef Base, StringRef Member, unsigned &Offset, SourceLocation AsmLoc); ExprResult LookupInlineAsmVarDeclField(Expr *RefExpr, StringRef Member, SourceLocation AsmLoc); StmtResult ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc, ArrayRef<Token> AsmToks, StringRef AsmString, unsigned NumOutputs, unsigned NumInputs, ArrayRef<StringRef> Constraints, ArrayRef<StringRef> Clobbers, ArrayRef<Expr*> Exprs, SourceLocation EndLoc); LabelDecl *GetOrCreateMSAsmLabel(StringRef ExternalLabelName, SourceLocation Location, bool AlwaysCreate); VarDecl *BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid = false); Decl *ActOnObjCExceptionDecl(Scope *S, Declarator &D); StmtResult ActOnObjCAtCatchStmt(SourceLocation AtLoc, SourceLocation RParen, Decl *Parm, Stmt *Body); StmtResult ActOnObjCAtFinallyStmt(SourceLocation AtLoc, Stmt *Body); StmtResult ActOnObjCAtTryStmt(SourceLocation AtLoc, Stmt *Try, MultiStmtArg Catch, Stmt *Finally); StmtResult BuildObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw); StmtResult ActOnObjCAtThrowStmt(SourceLocation AtLoc, Expr *Throw, Scope *CurScope); ExprResult ActOnObjCAtSynchronizedOperand(SourceLocation atLoc, Expr *operand); StmtResult ActOnObjCAtSynchronizedStmt(SourceLocation AtLoc, Expr *SynchExpr, Stmt *SynchBody); StmtResult ActOnObjCAutoreleasePoolStmt(SourceLocation AtLoc, Stmt *Body); VarDecl *BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id); Decl *ActOnExceptionDeclarator(Scope *S, Declarator &D); StmtResult ActOnCXXCatchBlock(SourceLocation CatchLoc, Decl *ExDecl, Stmt *HandlerBlock); StmtResult ActOnCXXTryBlock(SourceLocation TryLoc, Stmt *TryBlock, ArrayRef<Stmt *> Handlers); StmtResult ActOnSEHTryBlock(bool IsCXXTry, // try (true) or __try (false) ? SourceLocation TryLoc, Stmt *TryBlock, Stmt *Handler); StmtResult ActOnSEHExceptBlock(SourceLocation Loc, Expr *FilterExpr, Stmt *Block); void ActOnStartSEHFinallyBlock(); void ActOnAbortSEHFinallyBlock(); StmtResult ActOnFinishSEHFinallyBlock(SourceLocation Loc, Stmt *Block); StmtResult ActOnSEHLeaveStmt(SourceLocation Loc, Scope *CurScope); void DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock); bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const; /// If it's a file scoped decl that must warn if not used, keep track /// of it. void MarkUnusedFileScopedDecl(const DeclaratorDecl *D); /// DiagnoseUnusedExprResult - If the statement passed in is an expression /// whose result is unused, warn. void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID); void DiagnoseUnusedNestedTypedefs(const RecordDecl *D); void DiagnoseUnusedDecl(const NamedDecl *ND); /// If VD is set but not otherwise used, diagnose, for a parameter or a /// variable. void DiagnoseUnusedButSetDecl(const VarDecl *VD); /// 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() { ParsingClassDepth++; return DelayedDiagnostics.pushUndelayed(); } void PopParsingClass(ParsingClassState state) { ParsingClassDepth--; DelayedDiagnostics.popUndelayed(state); } void redelayDiagnostics(sema::DelayedDiagnosticPool &pool); void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReceiver = nullptr); bool makeUnavailableInSystemHeader(SourceLocation loc, UnavailableAttr::ImplicitReason reason); /// Issue any -Wunguarded-availability warnings in \c FD void DiagnoseUnguardedAvailabilityViolations(Decl *FD); void handleDelayedAvailabilityCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); //===--------------------------------------------------------------------===// // Expression Parsing Callbacks: SemaExpr.cpp. bool CanUseDecl(NamedDecl *D, bool TreatUnavailableAsInvalid); bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef<SourceLocation> Locs, const ObjCInterfaceDecl *UnknownObjCClass = nullptr, bool ObjCPropertyAccess = false, bool AvoidPartialAvailabilityChecks = false, ObjCInterfaceDecl *ClassReciever = nullptr); void NoteDeletedFunction(FunctionDecl *FD); void NoteDeletedInheritingConstructor(CXXConstructorDecl *CD); bool DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *PD, ObjCMethodDecl *Getter, SourceLocation Loc); void DiagnoseSentinelCalls(NamedDecl *D, SourceLocation Loc, ArrayRef<Expr *> Args); void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl = nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); enum ReuseLambdaContextDecl_t { ReuseLambdaContextDecl }; void PushExpressionEvaluationContext( ExpressionEvaluationContext NewContext, ReuseLambdaContextDecl_t, ExpressionEvaluationContextRecord::ExpressionKind Type = ExpressionEvaluationContextRecord::EK_Other); void PopExpressionEvaluationContext(); void DiscardCleanupsInEvaluationContext(); ExprResult TransformToPotentiallyEvaluated(Expr *E); ExprResult HandleExprEvaluationContextForTypeof(Expr *E); ExprResult CheckUnevaluatedOperand(Expr *E); void CheckUnusedVolatileAssignment(Expr *E); ExprResult ActOnConstantExpression(ExprResult Res); // Functions for marking a declaration referenced. These functions also // contain the relevant logic for marking if a reference to a function or // variable is an odr-use (in the C++11 sense). There are separate variants // for expressions referring to a decl; these exist because odr-use marking // needs to be delayed for some constant variables when we build one of the // named expressions. // // MightBeOdrUse indicates whether the use could possibly be an odr-use, and // should usually be true. This only needs to be set to false if the lack of // odr-use cannot be determined from the current context (for instance, // because the name denotes a virtual function and was written without an // explicit nested-name-specifier). void MarkAnyDeclReferenced(SourceLocation Loc, Decl *D, bool MightBeOdrUse); void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse = true); void MarkVariableReferenced(SourceLocation Loc, VarDecl *Var); void MarkDeclRefReferenced(DeclRefExpr *E, const Expr *Base = nullptr); void MarkMemberReferenced(MemberExpr *E); void MarkFunctionParmPackReferenced(FunctionParmPackExpr *E); void MarkCaptureUsedInEnclosingContext(VarDecl *Capture, SourceLocation Loc, unsigned CapturingScopeIndex); ExprResult CheckLValueToRValueConversionOperand(Expr *E); void CleanupVarDeclMarking(); enum TryCaptureKind { TryCapture_Implicit, TryCapture_ExplicitByVal, TryCapture_ExplicitByRef }; /// Try to capture the given variable. /// /// \param Var The variable to capture. /// /// \param Loc The location at which the capture occurs. /// /// \param Kind The kind of capture, which may be implicit (for either a /// block or a lambda), or explicit by-value or by-reference (for a lambda). /// /// \param EllipsisLoc The location of the ellipsis, if one is provided in /// an explicit lambda capture. /// /// \param BuildAndDiagnose Whether we are actually supposed to add the /// captures or diagnose errors. If false, this routine merely check whether /// the capture can occur without performing the capture itself or complaining /// if the variable cannot be captured. /// /// \param CaptureType Will be set to the type of the field used to capture /// this variable in the innermost block or lambda. Only valid when the /// variable can be captured. /// /// \param DeclRefType Will be set to the type of a reference to the capture /// from within the current scope. Only valid when the variable can be /// captured. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// variables that may or may not be used in certain specializations of /// a nested generic lambda. /// /// \returns true if an error occurred (i.e., the variable cannot be /// captured) and false if the capture succeeded. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt); /// Try to capture the given variable. bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind = TryCapture_Implicit, SourceLocation EllipsisLoc = SourceLocation()); /// Checks if the variable must be captured. bool NeedToCaptureVariable(VarDecl *Var, SourceLocation Loc); /// Given a variable, determine the type that a reference to that /// variable will have in the given scope. QualType getCapturedDeclRefType(VarDecl *Var, SourceLocation Loc); /// Mark all of the declarations referenced within a particular AST node as /// referenced. Used when template instantiation instantiates a non-dependent /// type -- entities referenced by the type are now referenced. void MarkDeclarationsReferencedInType(SourceLocation Loc, QualType T); void MarkDeclarationsReferencedInExpr(Expr *E, bool SkipLocalVariables = false, ArrayRef<const Expr *> StopAt = None); /// Try to recover by turning the given expression into a /// call. Returns true if recovery was attempted or an error was /// emitted; this may also leave the ExprResult invalid. bool tryToRecoverWithCall(ExprResult &E, const PartialDiagnostic &PD, bool ForceComplain = false, bool (*IsPlausibleResult)(QualType) = nullptr); /// Figure out if an expression could be turned into a call. bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads); /// Try to convert an expression \p E to type \p Ty. Returns the result of the /// conversion. ExprResult tryConvertExprToType(Expr *E, QualType Ty); /// Conditionally issue a diagnostic based on the statements's reachability /// analysis. /// /// \param Stmts If Stmts is non-empty, 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 DiagIfReachable(SourceLocation Loc, ArrayRef<const Stmt *> Stmts, const PartialDiagnostic &PD); /// Conditionally issue a diagnostic based on the current /// evaluation context. /// /// \param Statement If Statement is non-null, delay reporting the /// diagnostic until the function body is parsed, and then do a basic /// reachability analysis to determine if the statement is reachable. /// If it is unreachable, the diagnostic will not be emitted. bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD); /// Similar, but diagnostic is only produced if all the specified statements /// are reachable. bool DiagRuntimeBehavior(SourceLocation Loc, ArrayRef<const Stmt*> Stmts, const PartialDiagnostic &PD); // Primary Expressions. SourceRange getExprRange(Expr *E) const; ExprResult ActOnIdExpression( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Id, bool HasTrailingLParen, bool IsAddressOfOperand, CorrectionCandidateCallback *CCC = nullptr, bool IsInlineAsmIdentifier = false, Token *KeywordReplacement = nullptr); void DecomposeUnqualifiedId(const UnqualifiedId &Id, TemplateArgumentListInfo &Buffer, DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *&TemplateArgs); bool DiagnoseDependentMemberLookup(LookupResult &R); bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr, ArrayRef<Expr *> Args = None, TypoExpr **Out = nullptr); DeclResult LookupIvarInObjCMethod(LookupResult &Lookup, Scope *S, IdentifierInfo *II); ExprResult BuildIvarRefExpr(Scope *S, SourceLocation Loc, ObjCIvarDecl *IV); ExprResult LookupInObjCMethod(LookupResult &LookUp, Scope *S, IdentifierInfo *II, bool AllowBuiltinCreation=false); ExprResult ActOnDependentIdExpression(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, bool isAddressOfOperand, const TemplateArgumentListInfo *TemplateArgs); /// If \p D cannot be odr-used in the current expression evaluation context, /// return a reason explaining why. Otherwise, return NOUR_None. NonOdrUseReason getNonOdrUseReasonInCurrentContext(ValueDecl *D); DeclRefExpr *BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, SourceLocation Loc, const CXXScopeSpec *SS = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, const CXXScopeSpec *SS = nullptr, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); DeclRefExpr * BuildDeclRefExpr(ValueDecl *D, QualType Ty, ExprValueKind VK, const DeclarationNameInfo &NameInfo, NestedNameSpecifierLoc NNS, NamedDecl *FoundD = nullptr, SourceLocation TemplateKWLoc = SourceLocation(), const TemplateArgumentListInfo *TemplateArgs = nullptr); ExprResult BuildAnonymousStructUnionMemberReference( const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl = DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr = nullptr, SourceLocation opLoc = SourceLocation()); ExprResult BuildPossibleImplicitMemberExpr( const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, UnresolvedLookupExpr *AsULE = nullptr); ExprResult BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, bool IsDefiniteInstance, const Scope *S); bool UseArgumentDependentLookup(const CXXScopeSpec &SS, const LookupResult &R, bool HasTrailingLParen); ExprResult BuildQualifiedDeclarationNameExpr(CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, bool IsAddressOfOperand, const Scope *S, TypeSourceInfo **RecoveryTSI = nullptr); ExprResult BuildDependentDeclRefExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl = false); ExprResult BuildDeclarationNameExpr( const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D, NamedDecl *FoundD = nullptr, const TemplateArgumentListInfo *TemplateArgs = nullptr, bool AcceptInvalidDecl = false); ExprResult BuildLiteralOperatorCall(LookupResult &R, DeclarationNameInfo &SuffixInfo, ArrayRef<Expr *> Args, SourceLocation LitEndLoc, TemplateArgumentListInfo *ExplicitTemplateArgs = nullptr); ExprResult BuildPredefinedExpr(SourceLocation Loc, PredefinedExpr::IdentKind IK); ExprResult ActOnPredefinedExpr(SourceLocation Loc, tok::TokenKind Kind); ExprResult ActOnIntegerConstant(SourceLocation Loc, uint64_t Val); ExprResult BuildSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, TypeSourceInfo *TSI); ExprResult ActOnSYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, ParsedType ParsedTy); ExprResult BuildSYCLUniqueStableIdExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); ExprResult ActOnSYCLUniqueStableIdExpr(SourceLocation OpLoc, SourceLocation LParen, SourceLocation RParen, Expr *E); bool CheckLoopHintExpr(Expr *E, SourceLocation Loc); ExprResult ActOnNumericConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnCharacterConstant(const Token &Tok, Scope *UDLScope = nullptr); ExprResult ActOnParenExpr(SourceLocation L, SourceLocation R, Expr *E); ExprResult ActOnParenListExpr(SourceLocation L, SourceLocation R, MultiExprArg Val); /// ActOnStringLiteral - The specified tokens were lexed as pasted string /// fragments (e.g. "foo" "bar" L"baz"). ExprResult ActOnStringLiteral(ArrayRef<Token> StringToks, Scope *UDLScope = nullptr); ExprResult ActOnGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<ParsedType> ArgTypes, ArrayRef<Expr *> ArgExprs); ExprResult CreateGenericSelectionExpr(SourceLocation KeyLoc, SourceLocation DefaultLoc, SourceLocation RParenLoc, Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> Types, ArrayRef<Expr *> Exprs); // Binary/Unary Operators. 'Tok' is the token for the operator. ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr); ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input); ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input); bool isQualifiedMemberAccess(Expr *E); QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc); ExprResult CreateUnaryExprOrTypeTraitExpr(TypeSourceInfo *TInfo, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, SourceRange R); ExprResult CreateUnaryExprOrTypeTraitExpr(Expr *E, SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnUnaryExprOrTypeTraitExpr(SourceLocation OpLoc, UnaryExprOrTypeTrait ExprKind, bool IsType, void *TyOrEx, SourceRange ArgRange); ExprResult CheckPlaceholderExpr(Expr *E); bool CheckVecStepExpr(Expr *E); bool CheckUnaryExprOrTypeTraitOperand(Expr *E, UnaryExprOrTypeTrait ExprKind); bool CheckUnaryExprOrTypeTraitOperand(QualType ExprType, SourceLocation OpLoc, SourceRange ExprRange, UnaryExprOrTypeTrait ExprKind); ExprResult ActOnSizeofParameterPackExpr(Scope *S, SourceLocation OpLoc, IdentifierInfo &Name, SourceLocation NameLoc, SourceLocation RParenLoc); ExprResult ActOnPostfixUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Kind, Expr *Input); ExprResult ActOnArraySubscriptExpr(Scope *S, Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinArraySubscriptExpr(Expr *Base, SourceLocation LLoc, Expr *Idx, SourceLocation RLoc); ExprResult CreateBuiltinMatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, SourceLocation RBLoc); ExprResult ActOnOMPArraySectionExpr(Expr *Base, SourceLocation LBLoc, Expr *LowerBound, SourceLocation ColonLocFirst, SourceLocation ColonLocSecond, Expr *Length, Expr *Stride, SourceLocation RBLoc); ExprResult ActOnOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc, SourceLocation RParenLoc, ArrayRef<Expr *> Dims, ArrayRef<SourceRange> Brackets); /// Data structure for iterator expression. struct OMPIteratorData { IdentifierInfo *DeclIdent = nullptr; SourceLocation DeclIdentLoc; ParsedType Type; OMPIteratorExpr::IteratorRange Range; SourceLocation AssignLoc; SourceLocation ColonLoc; SourceLocation SecColonLoc; }; ExprResult ActOnOMPIteratorExpr(Scope *S, SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc, ArrayRef<OMPIteratorData> Data); // This struct is for use by ActOnMemberAccess to allow // BuildMemberReferenceExpr to be able to reinvoke ActOnMemberAccess after // changing the access operator from a '.' to a '->' (to see if that is the // change needed to fix an error about an unknown member, e.g. when the class // defines a custom operator->). struct ActOnMemberAccessExtraArgs { Scope *S; UnqualifiedId &Id; Decl *ObjCImpDecl; }; ExprResult BuildMemberReferenceExpr( Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildMemberReferenceExpr(Expr *Base, QualType BaseType, SourceLocation OpLoc, bool IsArrow, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, LookupResult &R, const TemplateArgumentListInfo *TemplateArgs, const Scope *S, bool SuppressQualifierCheck = false, ActOnMemberAccessExtraArgs *ExtraArgs = nullptr); ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo); ExprResult PerformMemberExprBaseConversion(Expr *Base, bool IsArrow); bool CheckQualifiedMemberReference(Expr *BaseExpr, QualType BaseType, const CXXScopeSpec &SS, const LookupResult &R); ExprResult ActOnDependentMemberExpr(Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierInScope, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec *SS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); MemberExpr * BuildMemberExpr(Expr *Base, bool IsArrow, SourceLocation OpLoc, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, ValueDecl *Member, DeclAccessPair FoundDecl, bool HadMultipleCandidates, const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK, ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr); void ActOnDefaultCtorInitializers(Decl *CDtorDecl); bool ConvertArgumentsForCall(CallExpr *Call, Expr *Fn, FunctionDecl *FDecl, const FunctionProtoType *Proto, ArrayRef<Expr *> Args, SourceLocation RParenLoc, bool ExecConfig = false); void CheckStaticArrayArgument(SourceLocation CallLoc, ParmVarDecl *Param, const Expr *ArgExpr); /// ActOnCallExpr - Handle a call to Fn with the specified array of arguments. /// This provides the location of the left/right parens and a list of comma /// locations. ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr); ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig = nullptr, bool IsExecConfig = false, bool AllowRecovery = false); Expr *BuildBuiltinCallExpr(SourceLocation Loc, Builtin::ID Id, MultiExprArg CallArgs); enum class AtomicArgumentOrder { API, AST }; ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder = AtomicArgumentOrder::API); ExprResult BuildResolvedCallExpr(Expr *Fn, NamedDecl *NDecl, SourceLocation LParenLoc, ArrayRef<Expr *> Arg, SourceLocation RParenLoc, Expr *Config = nullptr, bool IsExecConfig = false, ADLCallKind UsesADL = ADLCallKind::NotADL); ExprResult ActOnCUDAExecConfigExpr(Scope *S, SourceLocation LLLLoc, MultiExprArg ExecConfig, SourceLocation GGGLoc); ExprResult ActOnCastExpr(Scope *S, SourceLocation LParenLoc, Declarator &D, ParsedType &Ty, SourceLocation RParenLoc, Expr *CastExpr); ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op); CastKind PrepareScalarCast(ExprResult &src, QualType destType); /// Build an altivec or OpenCL literal. ExprResult BuildVectorLiteral(SourceLocation LParenLoc, SourceLocation RParenLoc, Expr *E, TypeSourceInfo *TInfo); ExprResult MaybeConvertParenListExprToParenExpr(Scope *S, Expr *ME); ExprResult ActOnCompoundLiteral(SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc, Expr *InitExpr); ExprResult BuildCompoundLiteralExpr(SourceLocation LParenLoc, TypeSourceInfo *TInfo, SourceLocation RParenLoc, Expr *LiteralExpr); ExprResult ActOnInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult BuildInitList(SourceLocation LBraceLoc, MultiExprArg InitArgList, SourceLocation RBraceLoc); ExprResult ActOnDesignatedInitializer(Designation &Desig, SourceLocation EqualOrColonLoc, bool GNUSyntax, ExprResult Init); private: static BinaryOperatorKind ConvertTokenKindToBinaryOpcode(tok::TokenKind Kind); public: ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr); ExprResult BuildBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); ExprResult CreateBuiltinBinOp(SourceLocation OpLoc, BinaryOperatorKind Opc, Expr *LHSExpr, Expr *RHSExpr); void LookupBinOp(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opc, UnresolvedSetImpl &Functions); void DiagnoseCommaOperator(const Expr *LHS, SourceLocation Loc); /// ActOnConditionalOp - Parse a ?: operation. Note that 'LHS' may be null /// in the case of a the GNU conditional expr extension. ExprResult ActOnConditionalOp(SourceLocation QuestionLoc, SourceLocation ColonLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr); /// ActOnAddrLabel - Parse the GNU address of label extension: "&&foo". ExprResult ActOnAddrLabel(SourceLocation OpLoc, SourceLocation LabLoc, LabelDecl *TheDecl); void ActOnStartStmtExpr(); ExprResult ActOnStmtExpr(Scope *S, SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc); ExprResult BuildStmtExpr(SourceLocation LPLoc, Stmt *SubStmt, SourceLocation RPLoc, unsigned TemplateDepth); // Handle the final expression in a statement expression. ExprResult ActOnStmtExprResult(ExprResult E); void ActOnStmtExprError(); // __builtin_offsetof(type, identifier(.identifier|[expr])*) struct OffsetOfComponent { SourceLocation LocStart, LocEnd; bool isBrackets; // true if [expr], false if .ident union { IdentifierInfo *IdentInfo; Expr *E; } U; }; /// __builtin_offsetof(type, a.b[123][456].c) ExprResult BuildBuiltinOffsetOf(SourceLocation BuiltinLoc, TypeSourceInfo *TInfo, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); ExprResult ActOnBuiltinOffsetOf(Scope *S, SourceLocation BuiltinLoc, SourceLocation TypeLoc, ParsedType ParsedArgTy, ArrayRef<OffsetOfComponent> Components, SourceLocation RParenLoc); // __builtin_choose_expr(constExpr, expr1, expr2) ExprResult ActOnChooseExpr(SourceLocation BuiltinLoc, Expr *CondExpr, Expr *LHSExpr, Expr *RHSExpr, SourceLocation RPLoc); // __builtin_va_arg(expr, type) ExprResult ActOnVAArg(SourceLocation BuiltinLoc, Expr *E, ParsedType Ty, SourceLocation RPLoc); ExprResult BuildVAArgExpr(SourceLocation BuiltinLoc, Expr *E, TypeSourceInfo *TInfo, SourceLocation RPLoc); // __builtin_LINE(), __builtin_FUNCTION(), __builtin_FILE(), // __builtin_COLUMN() ExprResult ActOnSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc); // Build a potentially resolved SourceLocExpr. ExprResult BuildSourceLocExpr(SourceLocExpr::IdentKind Kind, SourceLocation BuiltinLoc, SourceLocation RPLoc, DeclContext *ParentContext); // __null ExprResult ActOnGNUNullExpr(SourceLocation TokenLoc); bool CheckCaseExpression(Expr *E); /// Describes the result of an "if-exists" condition check. enum IfExistsResult { /// The symbol exists. IER_Exists, /// The symbol does not exist. IER_DoesNotExist, /// The name is a dependent name, so the results will differ /// from one instantiation to the next. IER_Dependent, /// An error occurred. IER_Error }; IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, CXXScopeSpec &SS, const DeclarationNameInfo &TargetNameInfo); IfExistsResult CheckMicrosoftIfExistsSymbol(Scope *S, SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name); StmtResult BuildMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, NestedNameSpecifierLoc QualifierLoc, DeclarationNameInfo NameInfo, Stmt *Nested); StmtResult ActOnMSDependentExistsStmt(SourceLocation KeywordLoc, bool IsIfExists, CXXScopeSpec &SS, UnqualifiedId &Name, Stmt *Nested); //===------------------------- "Block" Extension ------------------------===// /// ActOnBlockStart - This callback is invoked when a block literal is /// started. void ActOnBlockStart(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockArguments - This callback allows processing of block arguments. /// If there are no arguments, this is still invoked. void ActOnBlockArguments(SourceLocation CaretLoc, Declarator &ParamInfo, Scope *CurScope); /// ActOnBlockError - If there is an error parsing a block, this callback /// is invoked to pop the information about the block from the action impl. void ActOnBlockError(SourceLocation CaretLoc, Scope *CurScope); /// ActOnBlockStmtExpr - This is called when the body of a block statement /// literal was successfully completed. ^(int x){...} ExprResult ActOnBlockStmtExpr(SourceLocation CaretLoc, Stmt *Body, Scope *CurScope); //===---------------------------- 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); ExprResult BuildAsTypeExpr(Expr *E, QualType DestTy, 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(); NamespaceDecl *getCachedCoroNamespace() { return CoroTraitsNamespaceCache; } CXXRecordDecl *getStdBadAlloc() const; EnumDecl *getStdAlignValT() const; private: // A cache representing if we've fully checked the various comparison category // types stored in ASTContext. The bit-index corresponds to the integer value // of a ComparisonCategoryType enumerator. llvm::SmallBitVector FullyCheckedComparisonCategories; ValueDecl *tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl, CXXScopeSpec &SS, ParsedType TemplateTypeTy, IdentifierInfo *MemberOrBase); public: enum class ComparisonCategoryUsage { /// The '<=>' operator was used in an expression and a builtin operator /// was selected. OperatorInExpression, /// A defaulted 'operator<=>' needed the comparison category. This /// typically only applies to 'std::strong_ordering', due to the implicit /// fallback return value. DefaultedOperator, }; /// Lookup the specified comparison category types in the standard /// library, an check the VarDecls possibly returned by the operator<=> /// builtins for that type. /// /// \return The type of the comparison category type corresponding to the /// specified Kind, or a null type if an error occurs QualType CheckComparisonCategoryType(ComparisonCategoryType Kind, SourceLocation Loc, ComparisonCategoryUsage Usage); /// Tests whether Ty is an instance of std::initializer_list and, if /// it is and Element is not NULL, assigns the element type to Element. bool isStdInitializerList(QualType Ty, QualType *Element); /// Looks for the std::initializer_list template and instantiates it /// with Element, or emits an error if it's not found. /// /// \returns The instantiated template, or null on error. QualType BuildStdInitializerList(QualType Element, SourceLocation Loc); /// Determine whether Ctor is an initializer-list constructor, as /// defined in [dcl.init.list]p2. bool isInitListConstructor(const FunctionDecl *Ctor); Decl *ActOnUsingDirective(Scope *CurScope, SourceLocation UsingLoc, SourceLocation NamespcLoc, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *NamespcName, const ParsedAttributesView &AttrList); void PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir); Decl *ActOnNamespaceAliasDef(Scope *CurScope, SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, CXXScopeSpec &SS, SourceLocation IdentLoc, IdentifierInfo *Ident); void FilterUsingLookup(Scope *S, LookupResult &lookup); void HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow); bool CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Target, const LookupResult &PreviousDecls, UsingShadowDecl *&PrevShadow); UsingShadowDecl *BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD, 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, const LookupResult *R = nullptr, const UsingDecl *UD = nullptr); NamedDecl *BuildUsingDeclaration( Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS, DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc, const ParsedAttributesView &AttrList, bool IsInstantiation, bool IsUsingIfExists); NamedDecl *BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, SourceLocation NameLoc, EnumDecl *ED); 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 *ActOnUsingEnumDeclaration(Scope *CurScope, AccessSpecifier AS, SourceLocation UsingLoc, SourceLocation EnumLoc, const DeclSpec &); Decl *ActOnAliasDeclaration(Scope *CurScope, AccessSpecifier AS, MultiTemplateParamsArg TemplateParams, SourceLocation UsingLoc, UnqualifiedId &Name, const ParsedAttributesView &AttrList, TypeResult Type, Decl *DeclFromDeclSpec); /// BuildCXXConstructExpr - Creates a complete call to a constructor, /// including handling of its default argument expressions. /// /// \param ConstructKind - a CXXConstructExpr::ConstructionKind ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); /// Build a CXXConstructExpr whose constructor has already been resolved if /// it denotes an inherited constructor. ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); // FIXME: Can we remove this and have the above BuildCXXConstructExpr check if // the constructor can be elidable? ExprResult BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl, CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg Exprs, bool HadMultipleCandidates, bool IsListInitialization, bool IsStdInitListInitialization, bool RequiresZeroInit, unsigned ConstructKind, SourceRange ParenRange); ExprResult BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field); /// Instantiate or parse a C++ default argument expression as necessary. /// Return true on error. bool CheckCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating /// the default expr if needed. ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); /// FinalizeVarWithDestructor - Prepare for calling destructor on the /// constructed variable. void FinalizeVarWithDestructor(VarDecl *VD, const RecordType *DeclInitType); /// Helper class that collects exception specifications for /// implicitly-declared special member functions. class ImplicitExceptionSpecification { // Pointer to allow copying Sema *Self; // We order exception specifications thus: // noexcept is the most restrictive, but is only used in C++11. // throw() comes next. // Then a throw(collected exceptions) // Finally no specification, which is expressed as noexcept(false). // throw(...) is used instead if any called function uses it. ExceptionSpecificationType ComputedEST; llvm::SmallPtrSet<CanQualType, 4> ExceptionsSeen; SmallVector<QualType, 4> Exceptions; void ClearExceptions() { ExceptionsSeen.clear(); Exceptions.clear(); } public: explicit ImplicitExceptionSpecification(Sema &Self) : Self(&Self), ComputedEST(EST_BasicNoexcept) { if (!Self.getLangOpts().CPlusPlus11) ComputedEST = EST_DynamicNone; } /// Get the computed exception specification type. ExceptionSpecificationType getExceptionSpecType() const { assert(!isComputedNoexcept(ComputedEST) && "noexcept(expr) should not be a possible result"); return ComputedEST; } /// The number of exceptions in the exception specification. unsigned size() const { return Exceptions.size(); } /// The set of exceptions in the exception specification. const QualType *data() const { return Exceptions.data(); } /// Integrate another called method into the collected data. void CalledDecl(SourceLocation CallLoc, const CXXMethodDecl *Method); /// Integrate an invoked expression into the collected data. void CalledExpr(Expr *E) { CalledStmt(E); } /// Integrate an invoked statement into the collected data. void CalledStmt(Stmt *S); /// Overwrite an EPI's exception specification with this /// computed exception specification. FunctionProtoType::ExceptionSpecInfo getExceptionSpec() const { FunctionProtoType::ExceptionSpecInfo ESI; ESI.Type = getExceptionSpecType(); if (ESI.Type == EST_Dynamic) { ESI.Exceptions = Exceptions; } else if (ESI.Type == EST_None) { /// C++11 [except.spec]p14: /// The exception-specification is noexcept(false) if the set of /// potential exceptions of the special member function contains "any" ESI.Type = EST_NoexceptFalse; ESI.NoexceptExpr = Self->ActOnCXXBoolLiteral(SourceLocation(), tok::kw_false).get(); } return ESI; } }; /// Evaluate the implicit exception specification for a defaulted /// special member function. void EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD); /// Check the given noexcept-specifier, convert its expression, and compute /// the appropriate ExceptionSpecificationType. ExprResult ActOnNoexceptSpec(Expr *NoexceptExpr, ExceptionSpecificationType &EST); /// Check the given exception-specification and update the /// exception specification information with the results. void checkExceptionSpecification(bool IsTopLevel, ExceptionSpecificationType EST, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr, SmallVectorImpl<QualType> &Exceptions, FunctionProtoType::ExceptionSpecInfo &ESI); /// Determine if we're in a case where we need to (incorrectly) eagerly /// parse an exception specification to work around a libstdc++ bug. bool isLibstdcxxEagerExceptionSpecHack(const Declarator &D); /// Add an exception-specification to the given member function /// (or member function template). The exception-specification was parsed /// after the method itself was declared. void actOnDelayedExceptionSpecification(Decl *Method, ExceptionSpecificationType EST, SourceRange SpecificationRange, ArrayRef<ParsedType> DynamicExceptions, ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr); class InheritedConstructorInfo; /// Determine if a special member function should have a deleted /// definition when it is defaulted. bool ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM, InheritedConstructorInfo *ICI = nullptr, bool Diagnose = false); /// Produce notes explaining why a defaulted function was defined as deleted. void DiagnoseDeletedDefaultedFunction(FunctionDecl *FD); /// Declare the implicit default constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// default constructor will be added. /// /// \returns The implicitly-declared default constructor. CXXConstructorDecl *DeclareImplicitDefaultConstructor( CXXRecordDecl *ClassDecl); /// DefineImplicitDefaultConstructor - Checks for feasibility of /// defining this constructor as the default constructor. void DefineImplicitDefaultConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit destructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// destructor will be added. /// /// \returns The implicitly-declared destructor. CXXDestructorDecl *DeclareImplicitDestructor(CXXRecordDecl *ClassDecl); /// DefineImplicitDestructor - Checks for feasibility of /// defining this destructor as the default destructor. void DefineImplicitDestructor(SourceLocation CurrentLocation, CXXDestructorDecl *Destructor); /// Build an exception spec for destructors that don't have one. /// /// C++11 says that user-defined destructors with no exception spec get one /// that looks as if the destructor was implicitly declared. void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor); /// Define the specified inheriting constructor. void DefineInheritingConstructor(SourceLocation UseLoc, CXXConstructorDecl *Constructor); /// Declare the implicit copy constructor for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy constructor will be added. /// /// \returns The implicitly-declared copy constructor. CXXConstructorDecl *DeclareImplicitCopyConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitCopyConstructor - Checks for feasibility of /// defining this constructor as the copy constructor. void DefineImplicitCopyConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit move constructor for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move constructor will be added. /// /// \returns The implicitly-declared move constructor, or NULL if it wasn't /// declared. CXXConstructorDecl *DeclareImplicitMoveConstructor(CXXRecordDecl *ClassDecl); /// DefineImplicitMoveConstructor - Checks for feasibility of /// defining this constructor as the move constructor. void DefineImplicitMoveConstructor(SourceLocation CurrentLocation, CXXConstructorDecl *Constructor); /// Declare the implicit copy assignment operator for the given class. /// /// \param ClassDecl The class declaration into which the implicit /// copy assignment operator will be added. /// /// \returns The implicitly-declared copy assignment operator. CXXMethodDecl *DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared copy assignment operator. void DefineImplicitCopyAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Declare the implicit move assignment operator for the given class. /// /// \param ClassDecl The Class declaration into which the implicit /// move assignment operator will be added. /// /// \returns The implicitly-declared move assignment operator, or NULL if it /// wasn't declared. CXXMethodDecl *DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl); /// Defines an implicitly-declared move assignment operator. void DefineImplicitMoveAssignment(SourceLocation CurrentLocation, CXXMethodDecl *MethodDecl); /// Force the declaration of any implicitly-declared members of this /// class. void ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class); /// Check a completed declaration of an implicit special member. void CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD); /// Determine whether the given function is an implicitly-deleted /// special member function. bool isImplicitlyDeleted(FunctionDecl *FD); /// Check whether 'this' shows up in the type of a static member /// function after the (naturally empty) cv-qualifier-seq would be. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionType(CXXMethodDecl *Method); /// Whether this' shows up in the exception specification of a static /// member function. bool checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method); /// Check whether 'this' shows up in the attributes of the given /// static member function. /// /// \returns true if an error occurred. bool checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method); /// MaybeBindToTemporary - If the passed in expression has a record type with /// a non-trivial destructor, this will return CXXBindTemporaryExpr. Otherwise /// it simply returns the passed in expression. ExprResult MaybeBindToTemporary(Expr *E); /// Wrap the expression in a ConstantExpr if it is a potential immediate /// invocation. ExprResult CheckForImmediateInvocation(ExprResult E, FunctionDecl *Decl); bool CompleteConstructorCall(CXXConstructorDecl *Constructor, QualType DeclInitType, 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); // Checks that the vector type should be initialized from a scalar // by splatting the value rather than populating a single element. // This is the case for AltiVecVector types as well as with // AltiVecPixel and AltiVecBool when -faltivec-src-compat=xl is specified. bool ShouldSplatAltivecScalarInCast(const VectorType *VecTy); // Checks if the -faltivec-src-compat=gcc option is specified. // If so, AltiVecVector, AltiVecBool and AltiVecPixel types are // treated the same way as they are when trying to initialize // these vectors on gcc (an error is emitted). bool CheckAltivecInitFromScalar(SourceRange R, QualType VecTy, QualType SrcTy); /// ActOnCXXNamedCast - Parse /// {dynamic,static,reinterpret,const,addrspace}_cast's. ExprResult ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, SourceLocation LAngleBracketLoc, Declarator &D, SourceLocation RAngleBracketLoc, SourceLocation LParenLoc, Expr *E, SourceLocation RParenLoc); ExprResult BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind, TypeSourceInfo *Ty, Expr *E, SourceRange AngleBrackets, SourceRange Parens); ExprResult ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &Dcl, ExprResult Operand, SourceLocation RParenLoc); ExprResult BuildBuiltinBitCastExpr(SourceLocation KWLoc, TypeSourceInfo *TSI, Expr *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXTypeId(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXTypeid - Parse typeid( something ). ExprResult ActOnCXXTypeid(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, TypeSourceInfo *Operand, SourceLocation RParenLoc); ExprResult BuildCXXUuidof(QualType TypeInfoType, SourceLocation TypeidLoc, Expr *Operand, SourceLocation RParenLoc); /// ActOnCXXUuidof - Parse __uuidof( something ). ExprResult ActOnCXXUuidof(SourceLocation OpLoc, SourceLocation LParenLoc, bool isType, void *TyOrExpr, SourceLocation RParenLoc); /// Handle a C++1z fold-expression: ( expr op ... op expr ). ExprResult ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS, tok::TokenKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc); ExprResult BuildCXXFoldExpr(UnresolvedLookupExpr *Callee, SourceLocation LParenLoc, Expr *LHS, BinaryOperatorKind Operator, SourceLocation EllipsisLoc, Expr *RHS, SourceLocation RParenLoc, Optional<unsigned> NumExpansions); ExprResult BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc, BinaryOperatorKind Operator); //// ActOnCXXThis - Parse 'this' pointer. ExprResult ActOnCXXThis(SourceLocation loc); /// Build a CXXThisExpr and mark it referenced in the current context. Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit); void MarkThisReferenced(CXXThisExpr *This); /// Try to retrieve the type of the 'this' pointer. /// /// \returns The type of 'this', if possible. Otherwise, returns a NULL type. QualType getCurrentThisType(); /// When non-NULL, the C++ 'this' expression is allowed despite the /// current context not being a non-static member function. In such cases, /// this provides the type used for 'this'. QualType CXXThisTypeOverride; /// RAII object used to temporarily allow the C++ 'this' expression /// to be used, with the given qualifiers on the current class type. class CXXThisScopeRAII { Sema &S; QualType OldCXXThisTypeOverride; bool Enabled; public: /// Introduce a new scope where 'this' may be allowed (when enabled), /// using the given declaration (which is either a class template or a /// class) along with the given qualifiers. /// along with the qualifiers placed on '*this'. CXXThisScopeRAII(Sema &S, Decl *ContextDecl, Qualifiers CXXThisTypeQuals, bool Enabled = true); ~CXXThisScopeRAII(); }; /// Make sure the value of 'this' is actually available in the current /// context, if it is a potentially evaluated context. /// /// \param Loc The location at which the capture of 'this' occurs. /// /// \param Explicit Whether 'this' is explicitly captured in a lambda /// capture list. /// /// \param FunctionScopeIndexToStopAt If non-null, it points to the index /// of the FunctionScopeInfo stack beyond which we do not attempt to capture. /// This is useful when enclosing lambdas must speculatively capture /// 'this' that may or may not be used in certain specializations of /// a nested generic lambda (depending on whether the name resolves to /// a non-static member function or a static function). /// \return returns 'true' if failed, 'false' if success. bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit = false, bool BuildAndDiagnose = true, const unsigned *const FunctionScopeIndexToStopAt = nullptr, bool ByCopy = false); /// Determine whether the given type is the type of *this that is used /// outside of the body of a member function for a type that is currently /// being defined. bool isThisOutsideMemberFunctionBody(QualType BaseType); /// ActOnCXXBoolLiteral - Parse {true,false} literals. ExprResult ActOnCXXBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); /// ActOnObjCBoolLiteral - Parse {__objc_yes,__objc_no} literals. ExprResult ActOnObjCBoolLiteral(SourceLocation OpLoc, tok::TokenKind Kind); ExprResult ActOnObjCAvailabilityCheckExpr(llvm::ArrayRef<AvailabilitySpec> AvailSpecs, SourceLocation AtLoc, SourceLocation RParen); /// ActOnCXXNullPtrLiteral - Parse 'nullptr'. ExprResult ActOnCXXNullPtrLiteral(SourceLocation Loc); //// ActOnCXXThrow - Parse throw expressions. ExprResult ActOnCXXThrow(Scope *S, SourceLocation OpLoc, Expr *expr); ExprResult BuildCXXThrow(SourceLocation OpLoc, Expr *Ex, bool IsThrownVarInScope); bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E); /// ActOnCXXTypeConstructExpr - Parse construction of a specified type. /// Can be interpreted either as function-style casting ("int(x)") /// or class type construction ("ClassType(x,y,z)") /// or creation of a value-initialized type ("int()"). ExprResult ActOnCXXTypeConstructExpr(ParsedType TypeRep, SourceLocation LParenOrBraceLoc, MultiExprArg Exprs, SourceLocation RParenOrBraceLoc, bool ListInitialization); ExprResult BuildCXXTypeConstructExpr(TypeSourceInfo *Type, SourceLocation LParenLoc, MultiExprArg Exprs, SourceLocation RParenLoc, bool ListInitialization); /// ActOnCXXNew - Parsed a C++ 'new' expression. ExprResult ActOnCXXNew(SourceLocation StartLoc, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, Declarator &D, Expr *Initializer); ExprResult BuildCXXNew(SourceRange Range, bool UseGlobal, SourceLocation PlacementLParen, MultiExprArg PlacementArgs, SourceLocation PlacementRParen, SourceRange TypeIdParens, QualType AllocType, TypeSourceInfo *AllocTypeInfo, Optional<Expr *> ArraySize, SourceRange DirectInitRange, Expr *Initializer); /// Determine whether \p FD is an aligned allocation or deallocation /// function that is unavailable. bool isUnavailableAlignedAllocationFunction(const FunctionDecl &FD) const; /// Produce diagnostics if \p FD is an aligned allocation or deallocation /// function that is unavailable. void diagnoseUnavailableAlignedAllocation(const FunctionDecl &FD, SourceLocation Loc); bool CheckAllocatedType(QualType AllocType, SourceLocation Loc, SourceRange R); /// The scope in which to find allocation functions. enum AllocationFunctionScope { /// Only look for allocation functions in the global scope. AFS_Global, /// Only look for allocation functions in the scope of the /// allocated class. AFS_Class, /// Look for allocation functions in both the global scope /// and in the scope of the allocated class. AFS_Both }; /// Finds the overloads of operator new and delete that are appropriate /// for the allocation. bool FindAllocationFunctions(SourceLocation StartLoc, SourceRange Range, AllocationFunctionScope NewScope, AllocationFunctionScope DeleteScope, QualType AllocType, bool IsArray, bool &PassAlignment, MultiExprArg PlaceArgs, FunctionDecl *&OperatorNew, FunctionDecl *&OperatorDelete, bool Diagnose = true); void DeclareGlobalNewDelete(); void DeclareGlobalAllocationFunction(DeclarationName Name, QualType Return, ArrayRef<QualType> Params); bool FindDeallocationFunction(SourceLocation StartLoc, CXXRecordDecl *RD, DeclarationName Name, FunctionDecl* &Operator, bool Diagnose = true); FunctionDecl *FindUsualDeallocationFunction(SourceLocation StartLoc, bool CanProvideSize, bool Overaligned, DeclarationName Name); FunctionDecl *FindDeallocationFunctionForDestructor(SourceLocation StartLoc, CXXRecordDecl *RD); /// ActOnCXXDelete - Parsed a C++ 'delete' expression ExprResult ActOnCXXDelete(SourceLocation StartLoc, bool UseGlobal, bool ArrayForm, Expr *Operand); void CheckVirtualDtorCall(CXXDestructorDecl *dtor, SourceLocation Loc, bool IsDelete, bool CallCanBeVirtual, bool WarnOnNonAbstractTypes, SourceLocation DtorLoc); ExprResult ActOnNoexceptExpr(SourceLocation KeyLoc, SourceLocation LParen, Expr *Operand, SourceLocation RParen); ExprResult BuildCXXNoexceptExpr(SourceLocation KeyLoc, Expr *Operand, SourceLocation RParen); /// Parsed one of the type trait support pseudo-functions. ExprResult ActOnTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<ParsedType> Args, SourceLocation RParenLoc); ExprResult BuildTypeTrait(TypeTrait Kind, SourceLocation KWLoc, ArrayRef<TypeSourceInfo *> Args, SourceLocation RParenLoc); /// ActOnArrayTypeTrait - Parsed one of the binary type trait support /// pseudo-functions. ExprResult ActOnArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, ParsedType LhsTy, Expr *DimExpr, SourceLocation RParen); ExprResult BuildArrayTypeTrait(ArrayTypeTrait ATT, SourceLocation KWLoc, TypeSourceInfo *TSInfo, Expr *DimExpr, SourceLocation RParen); /// ActOnExpressionTrait - Parsed one of the unary type trait support /// pseudo-functions. ExprResult ActOnExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult BuildExpressionTrait(ExpressionTrait OET, SourceLocation KWLoc, Expr *Queried, SourceLocation RParen); ExprResult ActOnStartCXXMemberReference(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, ParsedType &ObjectType, bool &MayBePseudoDestructor); ExprResult BuildPseudoDestructorExpr(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, const CXXScopeSpec &SS, TypeSourceInfo *ScopeType, SourceLocation CCLoc, SourceLocation TildeLoc, PseudoDestructorTypeStorage DestroyedType); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, UnqualifiedId &FirstTypeName, SourceLocation CCLoc, SourceLocation TildeLoc, UnqualifiedId &SecondTypeName); ExprResult ActOnPseudoDestructorExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, SourceLocation TildeLoc, const DeclSpec& DS); /// MaybeCreateExprWithCleanups - If the current full-expression /// requires any cleanups, surround it with a ExprWithCleanups node. /// Otherwise, just returns the passed-in expression. Expr *MaybeCreateExprWithCleanups(Expr *SubExpr); Stmt *MaybeCreateStmtWithCleanups(Stmt *SubStmt); ExprResult MaybeCreateExprWithCleanups(ExprResult SubExpr); MaterializeTemporaryExpr * CreateMaterializeTemporaryExpr(QualType T, Expr *Temporary, bool BoundToLvalueReference); ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue) { return ActOnFinishFullExpr( Expr, Expr ? Expr->getExprLoc() : SourceLocation(), DiscardedValue); } ExprResult ActOnFinishFullExpr(Expr *Expr, SourceLocation CC, bool DiscardedValue, bool IsConstexpr = false); StmtResult ActOnFinishFullStmt(Stmt *Stmt); // Marks SS invalid if it represents an incomplete type. bool RequireCompleteDeclContext(CXXScopeSpec &SS, DeclContext *DC); // Complete an enum decl, maybe without a scope spec. bool RequireCompleteEnumDecl(EnumDecl *D, SourceLocation L, CXXScopeSpec *SS = nullptr); DeclContext *computeDeclContext(QualType T); DeclContext *computeDeclContext(const CXXScopeSpec &SS, bool EnteringContext = false); bool isDependentScopeSpecifier(const CXXScopeSpec &SS); CXXRecordDecl *getCurrentInstantiationOf(NestedNameSpecifier *NNS); /// The parser has parsed a global nested-name-specifier '::'. /// /// \param CCLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXGlobalScopeSpecifier(SourceLocation CCLoc, CXXScopeSpec &SS); /// The parser has parsed a '__super' nested-name-specifier. /// /// \param SuperLoc The location of the '__super' keyword. /// /// \param ColonColonLoc The location of the '::'. /// /// \param SS The nested-name-specifier, which will be updated in-place /// to reflect the parsed nested-name-specifier. /// /// \returns true if an error occurred, false otherwise. bool ActOnSuperScopeSpecifier(SourceLocation SuperLoc, SourceLocation ColonColonLoc, CXXScopeSpec &SS); bool isAcceptableNestedNameSpecifier(const NamedDecl *SD, bool *CanCorrect = nullptr); NamedDecl *FindFirstQualifierInScope(Scope *S, NestedNameSpecifier *NNS); /// Keeps information about an identifier in a nested-name-spec. /// struct NestedNameSpecInfo { /// The type of the object, if we're parsing nested-name-specifier in /// a member access expression. ParsedType ObjectType; /// The identifier preceding the '::'. IdentifierInfo *Identifier; /// The location of the identifier. SourceLocation IdentifierLoc; /// The location of the '::'. SourceLocation CCLoc; /// Creates info object for the most typical case. NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, ParsedType ObjectType = ParsedType()) : ObjectType(ObjectType), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } NestedNameSpecInfo(IdentifierInfo *II, SourceLocation IdLoc, SourceLocation ColonColonLoc, QualType ObjectType) : ObjectType(ParsedType::make(ObjectType)), Identifier(II), IdentifierLoc(IdLoc), CCLoc(ColonColonLoc) { } }; bool isNonTypeNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo); bool BuildCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, NamedDecl *ScopeLookupResult, bool ErrorRecoveryLookup, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); /// The parser has parsed a nested-name-specifier 'identifier::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param IdInfo Parser information about an identifier in the /// nested-name-spec. /// /// \param EnteringContext Whether we're entering the context nominated by /// this nested-name-specifier. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param ErrorRecoveryLookup If true, then this method is called to improve /// error recovery. In this case do not emit error message. /// /// \param IsCorrectedToColon If not null, suggestions to replace '::' -> ':' /// are allowed. The bool value pointed by this parameter is set to 'true' /// if the identifier is treated as if it was followed by ':', not '::'. /// /// \param OnlyNamespace If true, only considers namespaces in lookup. /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, NestedNameSpecInfo &IdInfo, bool EnteringContext, CXXScopeSpec &SS, bool ErrorRecoveryLookup = false, bool *IsCorrectedToColon = nullptr, bool OnlyNamespace = false); ExprResult ActOnDecltypeExpression(Expr *E); bool ActOnCXXNestedNameSpecifierDecltype(CXXScopeSpec &SS, const DeclSpec &DS, SourceLocation ColonColonLoc); bool IsInvalidUnlessNestedName(Scope *S, CXXScopeSpec &SS, NestedNameSpecInfo &IdInfo, bool EnteringContext); /// The parser has parsed a nested-name-specifier /// 'template[opt] template-name < template-args >::'. /// /// \param S The scope in which this nested-name-specifier occurs. /// /// \param SS The nested-name-specifier, which is both an input /// parameter (the nested-name-specifier before this type) and an /// output parameter (containing the full nested-name-specifier, /// including this new type). /// /// \param TemplateKWLoc the location of the 'template' keyword, if any. /// \param TemplateName the template name. /// \param TemplateNameLoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). /// \param CCLoc The location of the '::'. /// /// \param EnteringContext Whether we're entering the context of the /// nested-name-specifier. /// /// /// \returns true if an error occurred, false otherwise. bool ActOnCXXNestedNameSpecifier(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateName, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, SourceLocation CCLoc, bool EnteringContext); /// Given a C++ nested-name-specifier, produce an annotation value /// that the parser can use later to reconstruct the given /// nested-name-specifier. /// /// \param SS A nested-name-specifier. /// /// \returns A pointer containing all of the information in the /// nested-name-specifier \p SS. void *SaveNestedNameSpecifierAnnotation(CXXScopeSpec &SS); /// Given an annotation pointer for a nested-name-specifier, restore /// the nested-name-specifier structure. /// /// \param Annotation The annotation pointer, produced by /// \c SaveNestedNameSpecifierAnnotation(). /// /// \param AnnotationRange The source range corresponding to the annotation. /// /// \param SS The nested-name-specifier that will be updated with the contents /// of the annotation pointer. void RestoreNestedNameSpecifierAnnotation(void *Annotation, SourceRange AnnotationRange, CXXScopeSpec &SS); bool ShouldEnterDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclaratorScope - Called when a C++ scope specifier (global /// scope or nested-name-specifier) is parsed, part of a declarator-id. /// After this method is called, according to [C++ 3.4.3p3], names should be /// looked up in the declarator-id's scope, until the declarator is parsed and /// ActOnCXXExitDeclaratorScope is called. /// The 'SS' should be a non-empty valid CXXScopeSpec. bool ActOnCXXEnterDeclaratorScope(Scope *S, CXXScopeSpec &SS); /// ActOnCXXExitDeclaratorScope - Called when a declarator that previously /// invoked ActOnCXXEnterDeclaratorScope(), is finished. 'SS' is the same /// CXXScopeSpec that was passed to ActOnCXXEnterDeclaratorScope as well. /// Used to indicate that names should revert to being looked up in the /// defining scope. void ActOnCXXExitDeclaratorScope(Scope *S, const CXXScopeSpec &SS); /// ActOnCXXEnterDeclInitializer - Invoked when we are about to parse an /// initializer for the declaration 'Dcl'. /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a /// static data member of class X, names should be looked up in the scope of /// class X. void ActOnCXXEnterDeclInitializer(Scope *S, Decl *Dcl); /// ActOnCXXExitDeclInitializer - Invoked after we are finished parsing an /// initializer for the declaration 'Dcl'. void ActOnCXXExitDeclInitializer(Scope *S, Decl *Dcl); /// Create a new lambda closure type. CXXRecordDecl *createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault); /// Start the definition of a lambda expression. CXXMethodDecl *startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef<ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause); /// Number lambda for linkage purposes if necessary. void handleLambdaNumbering( CXXRecordDecl *Class, CXXMethodDecl *Method, Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling = None); /// Endow the lambda scope info with the relevant properties. void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable); /// Perform initialization analysis of the init-capture and perform /// any implicit conversions such as an lvalue-to-rvalue conversion if /// not being used to initialize a reference. ParsedType actOnLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, IdentifierInfo *Id, LambdaCaptureInitKind InitKind, Expr *&Init) { return ParsedType::make(buildLambdaInitCaptureInitialization( Loc, ByRef, EllipsisLoc, None, Id, InitKind != LambdaCaptureInitKind::CopyInit, Init)); } QualType buildLambdaInitCaptureInitialization( SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init); /// Create a dummy variable within the declcontext of the lambda's /// call operator, for name lookup purposes for a lambda init capture. /// /// CodeGen handles emission of lambda captures, ignoring these dummy /// variables appropriately. VarDecl *createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init); /// Add an init-capture to a lambda scope. void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var); /// Note that we have finished the explicit captures for the /// given lambda. void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI); /// \brief This is called after parsing the explicit template parameter list /// on a lambda (if it exists) in C++2a. void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc, ExprResult RequiresClause); /// Introduce the lambda parameters into scope. void addLambdaParameters( ArrayRef<LambdaIntroducer::LambdaCapture> Captures, CXXMethodDecl *CallOperator, Scope *CurScope); /// Deduce a block or lambda's return type based on the return /// statements present in the body. void deduceClosureReturnType(sema::CapturingScopeInfo &CSI); /// ActOnStartOfLambdaDefinition - This is called just before we start /// parsing the body of a lambda; it analyzes the explicit captures and /// arguments, and sets up various data-structures for the body of the /// lambda. void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope); /// ActOnLambdaError - If there is an error parsing a lambda, this callback /// is invoked to pop the information about the lambda. void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation = false); /// ActOnLambdaExpr - This is called when the body of a lambda expression /// was successfully completed. ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope); /// Does copying/destroying the captured variable have side effects? bool CaptureHasSideEffects(const sema::Capture &From); /// Diagnose if an explicit lambda capture is unused. Returns true if a /// diagnostic is emitted. bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From); /// Build a FieldDecl suitable to hold the given capture. FieldDecl *BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture); /// Initialize the given capture with a suitable expression. ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping = false); /// Complete a lambda-expression having processed and attached the /// lambda body. ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI); /// Get the return type to use for a lambda's conversion function(s) to /// function pointer type, given the type of the call operator. QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC); /// Define the "body" of the conversion from a lambda object to a /// function pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToFunctionPointerConversion( SourceLocation CurrentLoc, CXXConversionDecl *Conv); /// Define the "body" of the conversion from a lambda object to a /// block pointer. /// /// This routine doesn't actually define a sensible body; rather, it fills /// in the initialization expression needed to copy the lambda object into /// the block, and IR generation actually generates the real body of the /// block pointer conversion. void DefineImplicitLambdaToBlockPointerConversion(SourceLocation CurrentLoc, CXXConversionDecl *Conv); ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src); /// Check whether the given expression is a valid constraint expression. /// A diagnostic is emitted if it is not, false is returned, and /// PossibleNonPrimary will be set to true if the failure might be due to a /// non-primary expression being used as an atomic constraint. bool CheckConstraintExpression(const Expr *CE, Token NextToken = Token(), bool *PossibleNonPrimary = nullptr, bool IsTrailingRequiresClause = false); private: /// Caches pairs of template-like decls whose associated constraints were /// checked for subsumption and whether or not the first's constraints did in /// fact subsume the second's. llvm::DenseMap<std::pair<NamedDecl *, NamedDecl *>, bool> SubsumptionCache; /// Caches the normalized associated constraints of declarations (concepts or /// constrained declarations). If an error occurred while normalizing the /// associated constraints of the template or concept, nullptr will be cached /// here. llvm::DenseMap<NamedDecl *, NormalizedConstraint *> NormalizationCache; llvm::ContextualFoldingSet<ConstraintSatisfaction, const ASTContext &> SatisfactionCache; public: const NormalizedConstraint * getNormalizedAssociatedConstraints( NamedDecl *ConstrainedDecl, ArrayRef<const Expr *> AssociatedConstraints); /// \brief Check whether the given declaration's associated constraints are /// at least as constrained than another declaration's according to the /// partial ordering of constraints. /// /// \param Result If no error occurred, receives the result of true if D1 is /// at least constrained than D2, and false otherwise. /// /// \returns true if an error occurred, false otherwise. bool IsAtLeastAsConstrained(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2, bool &Result); /// If D1 was not at least as constrained as D2, but would've been if a pair /// of atomic constraints involved had been declared in a concept and not /// repeated in two separate places in code. /// \returns true if such a diagnostic was emitted, false otherwise. bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(NamedDecl *D1, ArrayRef<const Expr *> AC1, NamedDecl *D2, ArrayRef<const Expr *> AC2); /// \brief Check whether the given list of constraint expressions are /// satisfied (as if in a 'conjunction') given template arguments. /// \param Template the template-like entity that triggered the constraints /// check (either a concept or a constrained entity). /// \param ConstraintExprs a list of constraint expressions, treated as if /// they were 'AND'ed together. /// \param TemplateArgs the list of template arguments to substitute into the /// constraint expression. /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// \param Satisfaction if true is returned, will contain details of the /// satisfaction, with enough information to diagnose an unsatisfied /// expression. /// \returns true if an error occurred and satisfaction could not be checked, /// false otherwise. bool CheckConstraintSatisfaction( const NamedDecl *Template, ArrayRef<const Expr *> ConstraintExprs, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction); /// \brief Check whether the given non-dependent constraint expression is /// satisfied. Returns false and updates Satisfaction with the satisfaction /// verdict if successful, emits a diagnostic and returns true if an error /// occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckConstraintSatisfaction(const Expr *ConstraintExpr, ConstraintSatisfaction &Satisfaction); /// Check whether the given function decl's trailing requires clause is /// satisfied, if any. Returns false and updates Satisfaction with the /// satisfaction verdict if successful, emits a diagnostic and returns true if /// an error occured and satisfaction could not be determined. /// /// \returns true if an error occurred, false otherwise. bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc = SourceLocation()); /// \brief Ensure that the given template arguments satisfy the constraints /// associated with the given template, emitting a diagnostic if they do not. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateArgs The converted, canonicalized template arguments. /// /// \param TemplateIDRange The source range of the template id that /// caused the constraints check. /// /// \returns true if the constrains are not satisfied or could not be checked /// for satisfaction, false if the constraints are satisfied. bool EnsureTemplateArgumentListConstraints(TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange TemplateIDRange); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. /// \param First whether this is the first time an unsatisfied constraint is /// diagnosed for this error. void DiagnoseUnsatisfiedConstraint(const ConstraintSatisfaction &Satisfaction, bool First = true); /// \brief Emit diagnostics explaining why a constraint expression was deemed /// unsatisfied. void DiagnoseUnsatisfiedConstraint(const ASTConstraintSatisfaction &Satisfaction, bool First = true); // ParseObjCStringLiteral - Parse Objective-C string literals. ExprResult ParseObjCStringLiteral(SourceLocation *AtLocs, ArrayRef<Expr *> Strings); ExprResult BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S); /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *" /// or "id" if NSNumber is unavailable. ExprResult BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number); ExprResult ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value); ExprResult BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements); /// BuildObjCBoxedExpr - builds an ObjCBoxedExpr AST node for the /// '@' prefixed parenthesized expression. The type of the expression will /// either be "NSNumber *", "NSString *" or "NSValue *" depending on the type /// of ValueType, which is allowed to be a built-in numeric type, "char *", /// "const char *" or C structure with attribute 'objc_boxable'. ExprResult BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr); ExprResult BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod); ExprResult BuildObjCDictionaryLiteral(SourceRange SR, MutableArrayRef<ObjCDictionaryElement> Elements); ExprResult BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc); ExprResult BuildCXXMemberCallExpr(Expr *Exp, NamedDecl *FoundDecl, CXXConversionDecl *Method, bool HadMultipleCandidates); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType Ty, SourceLocation RParenLoc); /// ParseObjCSelectorExpression - Build selector expression for \@selector ExprResult ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc, bool WarnMultipleSelectors); /// ParseObjCProtocolExpression - Build protocol expression for \@protocol ExprResult ParseObjCProtocolExpression(IdentifierInfo * ProtocolName, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc); //===--------------------------------------------------------------------===// // C++ Declarations // Decl *ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc, Expr *LangStr, SourceLocation LBraceLoc); Decl *ActOnFinishLinkageSpecification(Scope *S, Decl *LinkageSpec, SourceLocation RBraceLoc); //===--------------------------------------------------------------------===// // C++ Classes // CXXRecordDecl *getCurrentClass(Scope *S, const CXXScopeSpec *SS); bool isCurrentClassName(const IdentifierInfo &II, Scope *S, const CXXScopeSpec *SS = nullptr); bool isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS); bool ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc, SourceLocation ColonLoc, const ParsedAttributesView &Attrs); NamedDecl *ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, Expr *BitfieldWidth, const VirtSpecifiers &VS, InClassInitStyle InitStyle); void ActOnStartCXXInClassMemberInitializer(); void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, SourceLocation LParenLoc, ArrayRef<Expr *> Args, SourceLocation RParenLoc, SourceLocation EllipsisLoc); MemInitResult ActOnMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *InitList, SourceLocation EllipsisLoc); MemInitResult BuildMemInitializer(Decl *ConstructorD, Scope *S, CXXScopeSpec &SS, IdentifierInfo *MemberOrBase, ParsedType TemplateTypeTy, const DeclSpec &DS, SourceLocation IdLoc, Expr *Init, SourceLocation EllipsisLoc); MemInitResult BuildMemberInitializer(ValueDecl *Member, Expr *Init, SourceLocation IdLoc); MemInitResult BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo, Expr *Init, CXXRecordDecl *ClassDecl, SourceLocation EllipsisLoc); MemInitResult BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init, CXXRecordDecl *ClassDecl); bool SetDelegatingInitializer(CXXConstructorDecl *Constructor, CXXCtorInitializer *Initializer); bool SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors, ArrayRef<CXXCtorInitializer *> Initializers = None); void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation); /// MarkBaseAndMemberDestructorsReferenced - Given a record decl, /// mark all the non-trivial destructors of its members and bases as /// referenced. void MarkBaseAndMemberDestructorsReferenced(SourceLocation Loc, CXXRecordDecl *Record); /// Mark destructors of virtual bases of this class referenced. In the Itanium /// C++ ABI, this is done when emitting a destructor for any non-abstract /// class. In the Microsoft C++ ABI, this is done any time a class's /// destructor is referenced. void MarkVirtualBaseDestructorsReferenced( SourceLocation Location, CXXRecordDecl *ClassDecl, llvm::SmallPtrSetImpl<const RecordType *> *DirectVirtualBases = nullptr); /// Do semantic checks to allow the complete destructor variant to be emitted /// when the destructor is defined in another translation unit. In the Itanium /// C++ ABI, destructor variants are emitted together. In the MS C++ ABI, they /// can be emitted in separate TUs. To emit the complete variant, run a subset /// of the checks performed when emitting a regular destructor. void CheckCompleteDestructorVariant(SourceLocation CurrentLocation, CXXDestructorDecl *Dtor); /// The list of classes whose vtables have been used within /// this translation unit, and the source locations at which the /// first use occurred. typedef std::pair<CXXRecordDecl*, SourceLocation> VTableUse; /// The list of vtables that are required but have not yet been /// materialized. SmallVector<VTableUse, 16> VTableUses; /// The set of classes whose vtables have been used within /// this translation unit, and a bit that will be true if the vtable is /// required to be emitted (otherwise, it should be emitted only if needed /// by code generation). llvm::DenseMap<CXXRecordDecl *, bool> VTablesUsed; /// Load any externally-stored vtable uses. void LoadExternalVTableUses(); /// Note that the vtable for the given class was used at the /// given location. void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired = false); /// Mark the exception specifications of all virtual member functions /// in the given class as needed. void MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc, const CXXRecordDecl *RD); /// MarkVirtualMembersReferenced - Will mark all members of the given /// CXXRecordDecl referenced. void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly = false); /// Define all of the vtables that have been used in this /// translation unit and reference any virtual members used by those /// vtables. /// /// \returns true if any work was done, false otherwise. bool DefineUsedVTables(); void AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl); void ActOnMemInitializers(Decl *ConstructorDecl, SourceLocation ColonLoc, ArrayRef<CXXCtorInitializer*> MemInits, bool AnyErrors); /// Check class-level dllimport/dllexport attribute. The caller must /// ensure that referenceDLLExportedClassMethods is called some point later /// when all outer classes of Class are complete. void checkClassLevelDLLAttribute(CXXRecordDecl *Class); void checkClassLevelCodeSegAttribute(CXXRecordDecl *Class); void referenceDLLExportedClassMethods(); void propagateDLLAttrToBaseClassTemplate( CXXRecordDecl *Class, Attr *ClassAttr, ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc); /// Add gsl::Pointer attribute to std::container::iterator /// \param ND The declaration that introduces the name /// std::container::iterator. \param UnderlyingRecord The record named by ND. void inferGslPointerAttribute(NamedDecl *ND, CXXRecordDecl *UnderlyingRecord); /// Add [[gsl::Owner]] and [[gsl::Pointer]] attributes for std:: types. void inferGslOwnerPointerAttribute(CXXRecordDecl *Record); /// Add [[gsl::Pointer]] attributes for std:: types. void inferGslPointerAttribute(TypedefNameDecl *TD); void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record); /// Check that the C++ class annoated with "trivial_abi" satisfies all the /// conditions that are needed for the attribute to have an effect. void checkIllFormedTrivialABIStruct(CXXRecordDecl &RD); void ActOnFinishCXXMemberSpecification(Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList); void ActOnFinishCXXMemberDecls(); void ActOnFinishCXXNonNestedClass(); void ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param); unsigned ActOnReenterTemplateScope(Decl *Template, llvm::function_ref<Scope *()> EnterScope); void ActOnStartDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnDelayedCXXMethodParameter(Scope *S, Decl *Param); void ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *Record); void ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *Method); void ActOnFinishDelayedMemberInitializers(Decl *Record); void MarkAsLateParsedTemplate(FunctionDecl *FD, Decl *FnD, CachedTokens &Toks); void UnmarkAsLateParsedTemplate(FunctionDecl *FD); bool IsInsideALocalClassWithinATemplateFunction(); Decl *ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, Expr *AssertMessageExpr, SourceLocation RParenLoc); Decl *BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc, Expr *AssertExpr, StringLiteral *AssertMessageExpr, SourceLocation RParenLoc, bool Failed); FriendDecl *CheckFriendTypeDecl(SourceLocation LocStart, SourceLocation FriendLoc, TypeSourceInfo *TSInfo); Decl *ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS, MultiTemplateParamsArg TemplateParams); NamedDecl *ActOnFriendFunctionDecl(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParams); QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass& SC); void CheckConstructor(CXXConstructorDecl *Constructor); QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass& SC); bool CheckDestructor(CXXDestructorDecl *Destructor); void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass& SC); Decl *ActOnConversionDeclarator(CXXConversionDecl *Conversion); void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC); void CheckDeductionGuideTemplate(FunctionTemplateDecl *TD); void CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *MD); bool CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM); void CheckDelayedMemberExceptionSpecs(); bool CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *MD, DefaultedComparisonKind DCK); void DeclareImplicitEqualityComparison(CXXRecordDecl *RD, FunctionDecl *Spaceship); void DefineDefaultedComparison(SourceLocation Loc, FunctionDecl *FD, DefaultedComparisonKind DCK); //===--------------------------------------------------------------------===// // C++ Derived Classes // /// ActOnBaseSpecifier - Parsed a base specifier CXXBaseSpecifier *CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc); BaseResult ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange, ParsedAttributes &Attrs, bool Virtual, AccessSpecifier Access, ParsedType basetype, SourceLocation BaseLoc, SourceLocation EllipsisLoc); bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef<CXXBaseSpecifier *> Bases); void ActOnBaseSpecifiers(Decl *ClassDecl, MutableArrayRef<CXXBaseSpecifier *> Bases); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base); bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base, CXXBasePaths &Paths); // FIXME: I don't like this name. void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, SourceLocation Loc, SourceRange Range, CXXCastPath *BasePath = nullptr, bool IgnoreAccess = false); bool CheckDerivedToBaseConversion(QualType Derived, QualType Base, unsigned InaccessibleBaseID, unsigned AmbiguousBaseConvID, SourceLocation Loc, SourceRange Range, DeclarationName Name, CXXCastPath *BasePath, bool IgnoreAccess = false); std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths); bool CheckOverridingFunctionAttributes(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionReturnType - Checks whether the return types are /// covariant, according to C++ [class.virtual]p5. bool CheckOverridingFunctionReturnType(const CXXMethodDecl *New, const CXXMethodDecl *Old); /// CheckOverridingFunctionExceptionSpec - Checks whether the exception /// spec is a subset of base spec. bool CheckOverridingFunctionExceptionSpec(const CXXMethodDecl *New, const CXXMethodDecl *Old); bool CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange); /// CheckOverrideControl - Check C++11 override control semantics. void CheckOverrideControl(NamedDecl *D); /// DiagnoseAbsenceOfOverrideControl - Diagnose if 'override' keyword was /// not used in the declaration of an overriding method. void DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent); /// CheckForFunctionMarkedFinal - Checks whether a virtual member function /// overrides a virtual member function marked 'final', according to /// C++11 [class.virtual]p4. bool CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New, const CXXMethodDecl *Old); //===--------------------------------------------------------------------===// // C++ Access Control // enum AccessResult { AR_accessible, AR_inaccessible, AR_dependent, AR_delayed }; bool SetMemberAccessSpecifier(NamedDecl *MemberDecl, NamedDecl *PrevMemberDecl, AccessSpecifier LexicalAS); AccessResult CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E, DeclAccessPair FoundDecl); AccessResult CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E, DeclAccessPair FoundDecl); AccessResult CheckAllocationAccess(SourceLocation OperatorLoc, SourceRange PlacementRange, CXXRecordDecl *NamingClass, DeclAccessPair FoundDecl, bool Diagnose = true); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, bool IsCopyBindingRefToTemp = false); AccessResult CheckConstructorAccess(SourceLocation Loc, CXXConstructorDecl *D, DeclAccessPair FoundDecl, const InitializedEntity &Entity, const PartialDiagnostic &PDiag); AccessResult CheckDestructorAccess(SourceLocation Loc, CXXDestructorDecl *Dtor, const PartialDiagnostic &PDiag, QualType objectType = QualType()); AccessResult CheckFriendAccess(NamedDecl *D); AccessResult CheckMemberAccess(SourceLocation UseLoc, CXXRecordDecl *NamingClass, DeclAccessPair Found); AccessResult CheckStructuredBindingMemberAccess(SourceLocation UseLoc, CXXRecordDecl *DecomposedClass, DeclAccessPair Field); AccessResult CheckMemberOperatorAccess(SourceLocation Loc, Expr *ObjectExpr, Expr *ArgExpr, DeclAccessPair FoundDecl); AccessResult CheckAddressOfMemberAccess(Expr *OvlExpr, DeclAccessPair FoundDecl); AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck = false, bool ForceUnprivileged = false); void CheckLookupAccess(const LookupResult &R); bool IsSimplyAccessible(NamedDecl *Decl, CXXRecordDecl *NamingClass, QualType BaseType); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType, SourceLocation Loc, const PartialDiagnostic &Diag); bool isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass, DeclAccessPair Found, QualType ObjectType) { return isMemberAccessibleForDeletion(NamingClass, Found, ObjectType, SourceLocation(), PDiag()); } void HandleDependentAccessCheck(const DependentDiagnostic &DD, const MultiLevelTemplateArgumentList &TemplateArgs); void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); void HandleDelayedAccessCheck(sema::DelayedDiagnostic &DD, Decl *Ctx); /// When true, access checking violations are treated as SFINAE /// failures rather than hard errors. bool AccessCheckingSFINAE; enum AbstractDiagSelID { AbstractNone = -1, AbstractReturnType, AbstractParamType, AbstractVariableType, AbstractFieldType, AbstractIvarType, AbstractSynthesizedIvarType, AbstractArrayType }; bool isAbstractType(SourceLocation Loc, QualType T); bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser); template <typename... Ts> bool RequireNonAbstractType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args) { BoundTypeDiagnoser<Ts...> Diagnoser(DiagID, Args...); return RequireNonAbstractType(Loc, T, Diagnoser); } void DiagnoseAbstractType(const CXXRecordDecl *RD); //===--------------------------------------------------------------------===// // C++ Overloaded Operators [C++ 13.5] // bool CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl); bool CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl); //===--------------------------------------------------------------------===// // C++ Templates [C++ 14] // void FilterAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true); bool hasAnyAcceptableTemplateNames(LookupResult &R, bool AllowFunctionTemplates = true, bool AllowDependent = true, bool AllowNonTemplateFunctions = false); /// Try to interpret the lookup result D as a template-name. /// /// \param D A declaration found by name lookup. /// \param AllowFunctionTemplates Whether function templates should be /// considered valid results. /// \param AllowDependent Whether unresolved using declarations (that might /// name templates) should be considered valid results. static NamedDecl *getAsTemplateNameDecl(NamedDecl *D, bool AllowFunctionTemplates = true, bool AllowDependent = true); enum TemplateNameIsRequiredTag { TemplateNameIsRequired }; /// Whether and why a template name is required in this lookup. class RequiredTemplateKind { public: /// Template name is required if TemplateKWLoc is valid. RequiredTemplateKind(SourceLocation TemplateKWLoc = SourceLocation()) : TemplateKW(TemplateKWLoc) {} /// Template name is unconditionally required. RequiredTemplateKind(TemplateNameIsRequiredTag) : TemplateKW() {} SourceLocation getTemplateKeywordLoc() const { return TemplateKW.getValueOr(SourceLocation()); } bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); } bool isRequired() const { return TemplateKW != SourceLocation(); } explicit operator bool() const { return isRequired(); } private: llvm::Optional<SourceLocation> TemplateKW; }; enum class AssumedTemplateKind { /// This is not assumed to be a template name. None, /// This is assumed to be a template name because lookup found nothing. FoundNothing, /// This is assumed to be a template name because lookup found one or more /// functions (but no function templates). FoundFunctions, }; bool LookupTemplateName( LookupResult &R, Scope *S, CXXScopeSpec &SS, QualType ObjectType, bool EnteringContext, bool &MemberOfUnknownSpecialization, RequiredTemplateKind RequiredTemplate = SourceLocation(), AssumedTemplateKind *ATK = nullptr, bool AllowTypoCorrection = true); TemplateNameKind isTemplateName(Scope *S, CXXScopeSpec &SS, bool hasTemplateKeyword, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool &MemberOfUnknownSpecialization, bool Disambiguation = false); /// Try to resolve an undeclared template name as a type template. /// /// Sets II to the identifier corresponding to the template name, and updates /// Name to a corresponding (typo-corrected) type template name and TNK to /// the corresponding kind, if possible. void ActOnUndeclaredTypeTemplateName(Scope *S, TemplateTy &Name, TemplateNameKind &TNK, SourceLocation NameLoc, IdentifierInfo *&II); bool resolveAssumedTemplateNameAsType(Scope *S, TemplateName &Name, SourceLocation NameLoc, bool Diagnose = true); /// Determine whether a particular identifier might be the name in a C++1z /// deduction-guide declaration. bool isDeductionGuideName(Scope *S, const IdentifierInfo &Name, SourceLocation NameLoc, ParsedTemplateTy *Template = nullptr); bool DiagnoseUnknownTemplateName(const IdentifierInfo &II, SourceLocation IILoc, Scope *S, const CXXScopeSpec *SS, TemplateTy &SuggestedTemplate, TemplateNameKind &SuggestedKind); bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain = true); void DiagnoseTemplateParameterShadow(SourceLocation Loc, Decl *PrevDecl); TemplateDecl *AdjustDeclIfTemplate(Decl *&Decl); NamedDecl *ActOnTypeParameter(Scope *S, bool Typename, SourceLocation EllipsisLoc, SourceLocation KeyLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedType DefaultArg, bool HasTypeConstraint); bool ActOnTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool BuildTypeConstraint(const CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc, bool AllowUnexpandedPack); bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool AttachTypeConstraint(AutoTypeLoc TL, NonTypeTemplateParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc); bool RequireStructuralType(QualType T, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(TypeSourceInfo *&TSI, SourceLocation Loc); QualType CheckNonTypeTemplateParameterType(QualType T, SourceLocation Loc); NamedDecl *ActOnNonTypeTemplateParameter(Scope *S, Declarator &D, unsigned Depth, unsigned Position, SourceLocation EqualLoc, Expr *DefaultArg); NamedDecl *ActOnTemplateTemplateParameter(Scope *S, SourceLocation TmpLoc, TemplateParameterList *Params, SourceLocation EllipsisLoc, IdentifierInfo *ParamName, SourceLocation ParamNameLoc, unsigned Depth, unsigned Position, SourceLocation EqualLoc, ParsedTemplateArgument DefaultArg); TemplateParameterList * ActOnTemplateParameterList(unsigned Depth, SourceLocation ExportLoc, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause); /// The context in which we are checking a template parameter list. enum TemplateParamListContext { TPC_ClassTemplate, TPC_VarTemplate, TPC_FunctionTemplate, TPC_ClassTemplateMember, TPC_FriendClassTemplate, TPC_FriendFunctionTemplate, TPC_FriendFunctionTemplateDefinition, TPC_TypeAliasTemplate }; bool CheckTemplateParameterList(TemplateParameterList *NewParams, TemplateParameterList *OldParams, TemplateParamListContext TPC, SkipBodyInfo *SkipBody = nullptr); TemplateParameterList *MatchTemplateParametersToScopeSpecifier( SourceLocation DeclStartLoc, SourceLocation DeclLoc, const CXXScopeSpec &SS, TemplateIdAnnotation *TemplateId, ArrayRef<TemplateParameterList *> ParamLists, bool IsFriend, bool &IsMemberSpecialization, bool &Invalid, bool SuppressDiagnostic = false); DeclResult CheckClassTemplate( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, TemplateParameterList *TemplateParams, AccessSpecifier AS, SourceLocation ModulePrivateLoc, SourceLocation FriendLoc, unsigned NumOuterTemplateParamLists, TemplateParameterList **OuterTemplateParamLists, SkipBodyInfo *SkipBody = nullptr); TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc); /// Get a template argument mapping the given template parameter to itself, /// e.g. for X in \c template<int X>, this would return an expression template /// argument referencing X. TemplateArgumentLoc getIdentityTemplateArgumentLoc(NamedDecl *Param, SourceLocation Location); void translateTemplateArguments(const ASTTemplateArgsPtr &In, TemplateArgumentListInfo &Out); ParsedTemplateArgument ActOnTemplateTypeArgument(TypeResult ParsedType); void NoteAllFoundTemplates(TemplateName Name); QualType CheckTemplateIdType(TemplateName Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs); TypeResult ActOnTemplateIdType(Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy Template, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, bool IsCtorOrDtorName = false, bool IsClassName = false); /// Parsed an elaborated-type-specifier that refers to a template-id, /// such as \c class T::template apply<U>. TypeResult ActOnTagTemplateIdType(TagUseKind TUK, TypeSpecifierType TagSpec, SourceLocation TagLoc, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, TemplateTy TemplateD, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgsIn, SourceLocation RAngleLoc); DeclResult ActOnVarTemplateSpecialization( Scope *S, Declarator &D, TypeSourceInfo *DI, SourceLocation TemplateKWLoc, TemplateParameterList *TemplateParams, StorageClass SC, bool IsPartialSpecialization); /// Get the specialization of the given variable template corresponding to /// the specified argument list, or a null-but-valid result if the arguments /// are dependent. DeclResult CheckVarTemplateId(VarTemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation TemplateNameLoc, const TemplateArgumentListInfo &TemplateArgs); /// Form a reference to the specialization of the given variable template /// corresponding to the specified argument list, or a null-but-valid result /// if the arguments are dependent. ExprResult CheckVarTemplateId(const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, VarTemplateDecl *Template, SourceLocation TemplateLoc, const TemplateArgumentListInfo *TemplateArgs); ExprResult CheckConceptTemplateId(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const TemplateArgumentListInfo *TemplateArgs); void diagnoseMissingTemplateArguments(TemplateName Name, SourceLocation Loc); ExprResult BuildTemplateIdExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R, bool RequiresADL, const TemplateArgumentListInfo *TemplateArgs); ExprResult BuildQualifiedTemplateIdExpr(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs); TemplateNameKind ActOnTemplateName( Scope *S, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, const UnqualifiedId &Name, ParsedType ObjectType, bool EnteringContext, TemplateTy &Template, bool AllowInjectedClassName = false); DeclResult ActOnClassTemplateSpecialization( Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, SourceLocation ModulePrivateLoc, CXXScopeSpec &SS, TemplateIdAnnotation &TemplateId, const ParsedAttributesView &Attr, MultiTemplateParamsArg TemplateParameterLists, SkipBodyInfo *SkipBody = nullptr); bool CheckTemplatePartialSpecializationArgs(SourceLocation Loc, TemplateDecl *PrimaryTemplate, unsigned NumExplicitArgs, ArrayRef<TemplateArgument> Args); void CheckTemplatePartialSpecialization( ClassTemplatePartialSpecializationDecl *Partial); void CheckTemplatePartialSpecialization( VarTemplatePartialSpecializationDecl *Partial); Decl *ActOnTemplateDeclarator(Scope *S, MultiTemplateParamsArg TemplateParameterLists, Declarator &D); bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind NewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew); bool CheckDependentFunctionTemplateSpecialization(FunctionDecl *FD, const TemplateArgumentListInfo &ExplicitTemplateArgs, LookupResult &Previous); bool CheckFunctionTemplateSpecialization( FunctionDecl *FD, TemplateArgumentListInfo *ExplicitTemplateArgs, LookupResult &Previous, bool QualifiedFriend = false); bool CheckMemberSpecialization(NamedDecl *Member, LookupResult &Previous); void CompleteMemberSpecialization(NamedDecl *Member, LookupResult &Previous); DeclResult ActOnExplicitInstantiation( Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, const CXXScopeSpec &SS, TemplateTy Template, SourceLocation TemplateNameLoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, unsigned TagSpec, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr); DeclResult ActOnExplicitInstantiation(Scope *S, SourceLocation ExternLoc, SourceLocation TemplateLoc, Declarator &D); TemplateArgumentLoc SubstDefaultTemplateArgumentIfAvailable(TemplateDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, Decl *Param, SmallVectorImpl<TemplateArgument> &Converted, bool &HasDefaultArg); /// Specifies the context in which a particular template /// argument is being checked. enum CheckTemplateArgumentKind { /// The template argument was specified in the code or was /// instantiated with some deduced template arguments. CTAK_Specified, /// The template argument was deduced via template argument /// deduction. CTAK_Deduced, /// The template argument was deduced from an array bound /// via template argument deduction. CTAK_DeducedFromArrayBound }; bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl<TemplateArgument> &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); /// Check that the given template arguments can be be provided to /// the given template, converting the arguments along the way. /// /// \param Template The template to which the template arguments are being /// provided. /// /// \param TemplateLoc The location of the template name in the source. /// /// \param TemplateArgs The list of template arguments. If the template is /// a template template parameter, this function may extend the set of /// template arguments to also include substituted, defaulted template /// arguments. /// /// \param PartialTemplateArgs True if the list of template arguments is /// intentionally partial, e.g., because we're checking just the initial /// set of template arguments. /// /// \param Converted Will receive the converted, canonicalized template /// arguments. /// /// \param UpdateArgsWithConversions If \c true, update \p TemplateArgs to /// contain the converted forms of the template arguments as written. /// Otherwise, \p TemplateArgs will not be modified. /// /// \param ConstraintsNotSatisfied If provided, and an error occured, will /// receive true if the cause for the error is the associated constraints of /// the template not being satisfied by the template arguments. /// /// \returns true if an error occurred, false otherwise. bool CheckTemplateArgumentList(TemplateDecl *Template, SourceLocation TemplateLoc, TemplateArgumentListInfo &TemplateArgs, bool PartialTemplateArgs, SmallVectorImpl<TemplateArgument> &Converted, bool UpdateArgsWithConversions = true, bool *ConstraintsNotSatisfied = nullptr); bool CheckTemplateTypeArgument(TemplateTypeParmDecl *Param, TemplateArgumentLoc &Arg, SmallVectorImpl<TemplateArgument> &Converted); bool CheckTemplateArgument(TypeSourceInfo *Arg); ExprResult CheckTemplateArgument(NonTypeTemplateParmDecl *Param, QualType InstantiatedParamType, Expr *Arg, TemplateArgument &Converted, CheckTemplateArgumentKind CTAK = CTAK_Specified); bool CheckTemplateTemplateArgument(TemplateTemplateParmDecl *Param, TemplateParameterList *Params, TemplateArgumentLoc &Arg); ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc); ExprResult BuildExpressionFromIntegralTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc); /// Enumeration describing how template parameter lists are compared /// for equality. enum TemplateParameterListEqualKind { /// We are matching the template parameter lists of two templates /// that might be redeclarations. /// /// \code /// template<typename T> struct X; /// template<typename T> struct X; /// \endcode TPL_TemplateMatch, /// We are matching the template parameter lists of two template /// template parameters as part of matching the template parameter lists /// of two templates that might be redeclarations. /// /// \code /// template<template<int I> class TT> struct X; /// template<template<int Value> class Other> struct X; /// \endcode TPL_TemplateTemplateParmMatch, /// We are matching the template parameter lists of a template /// template argument against the template parameter lists of a template /// template parameter. /// /// \code /// template<template<int Value> class Metafun> struct X; /// template<int Value> struct integer_c; /// X<integer_c> xic; /// \endcode TPL_TemplateTemplateArgumentMatch }; bool TemplateParameterListsAreEqual(TemplateParameterList *New, TemplateParameterList *Old, bool Complain, TemplateParameterListEqualKind Kind, SourceLocation TemplateArgLoc = SourceLocation()); bool CheckTemplateDeclScope(Scope *S, TemplateParameterList *TemplateParams); /// Called when the parser has parsed a C++ typename /// specifier, e.g., "typename T::type". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param II the identifier we're retrieving (e.g., 'type' in the example). /// \param IdLoc the location of the identifier. TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, const IdentifierInfo &II, SourceLocation IdLoc); /// Called when the parser has parsed a C++ typename /// specifier that ends in a template-id, e.g., /// "typename MetaFun::template apply<T1, T2>". /// /// \param S The scope in which this typename type occurs. /// \param TypenameLoc the location of the 'typename' keyword /// \param SS the nested-name-specifier following the typename (e.g., 'T::'). /// \param TemplateLoc the location of the 'template' keyword, if any. /// \param TemplateName The template name. /// \param TemplateII The identifier used to name the template. /// \param TemplateIILoc The location of the template name. /// \param LAngleLoc The location of the opening angle bracket ('<'). /// \param TemplateArgs The template arguments. /// \param RAngleLoc The location of the closing angle bracket ('>'). TypeResult ActOnTypenameType(Scope *S, SourceLocation TypenameLoc, const CXXScopeSpec &SS, SourceLocation TemplateLoc, TemplateTy TemplateName, IdentifierInfo *TemplateII, SourceLocation TemplateIILoc, SourceLocation LAngleLoc, ASTTemplateArgsPtr TemplateArgs, SourceLocation RAngleLoc); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, TypeSourceInfo **TSI, bool DeducedTSTContext); QualType CheckTypenameType(ElaboratedTypeKeyword Keyword, SourceLocation KeywordLoc, NestedNameSpecifierLoc QualifierLoc, const IdentifierInfo &II, SourceLocation IILoc, bool DeducedTSTContext = true); TypeSourceInfo *RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name); bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS); ExprResult RebuildExprInCurrentInstantiation(Expr *E); bool RebuildTemplateParamsInCurrentInstantiation( TemplateParameterList *Params); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args); std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgument *Args, unsigned NumArgs); //===--------------------------------------------------------------------===// // C++ Concepts //===--------------------------------------------------------------------===// Decl *ActOnConceptDefinition( Scope *S, MultiTemplateParamsArg TemplateParameterLists, IdentifierInfo *Name, SourceLocation NameLoc, Expr *ConstraintExpr); RequiresExprBodyDecl * ActOnStartRequiresExpr(SourceLocation RequiresKWLoc, ArrayRef<ParmVarDecl *> LocalParameters, Scope *BodyScope); void ActOnFinishRequiresExpr(); concepts::Requirement *ActOnSimpleRequirement(Expr *E); concepts::Requirement *ActOnTypeRequirement( SourceLocation TypenameKWLoc, CXXScopeSpec &SS, SourceLocation NameLoc, IdentifierInfo *TypeName, TemplateIdAnnotation *TemplateId); concepts::Requirement *ActOnCompoundRequirement(Expr *E, SourceLocation NoexceptLoc); concepts::Requirement * ActOnCompoundRequirement( Expr *E, SourceLocation NoexceptLoc, CXXScopeSpec &SS, TemplateIdAnnotation *TypeConstraint, unsigned Depth); concepts::Requirement *ActOnNestedRequirement(Expr *Constraint); concepts::ExprRequirement * BuildExprRequirement( Expr *E, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::ExprRequirement * BuildExprRequirement( concepts::Requirement::SubstitutionDiagnostic *ExprSubstDiag, bool IsSatisfied, SourceLocation NoexceptLoc, concepts::ExprRequirement::ReturnTypeRequirement ReturnTypeRequirement); concepts::TypeRequirement *BuildTypeRequirement(TypeSourceInfo *Type); concepts::TypeRequirement * BuildTypeRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); concepts::NestedRequirement *BuildNestedRequirement(Expr *E); concepts::NestedRequirement * BuildNestedRequirement( concepts::Requirement::SubstitutionDiagnostic *SubstDiag); ExprResult ActOnRequiresExpr(SourceLocation RequiresKWLoc, RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> LocalParameters, ArrayRef<concepts::Requirement *> Requirements, SourceLocation ClosingBraceLoc); //===--------------------------------------------------------------------===// // C++ Variadic Templates (C++0x [temp.variadic]) //===--------------------------------------------------------------------===// /// Determine whether an unexpanded parameter pack might be permitted in this /// location. Useful for error recovery. bool isUnexpandedParameterPackPermitted(); /// The context in which an unexpanded parameter pack is /// being diagnosed. /// /// Note that the values of this enumeration line up with the first /// argument to the \c err_unexpanded_parameter_pack diagnostic. enum UnexpandedParameterPackContext { /// An arbitrary expression. UPPC_Expression = 0, /// The base type of a class type. UPPC_BaseType, /// The type of an arbitrary declaration. UPPC_DeclarationType, /// The type of a data member. UPPC_DataMemberType, /// The size of a bit-field. UPPC_BitFieldWidth, /// The expression in a static assertion. UPPC_StaticAssertExpression, /// The fixed underlying type of an enumeration. UPPC_FixedUnderlyingType, /// The enumerator value. UPPC_EnumeratorValue, /// A using declaration. UPPC_UsingDeclaration, /// A friend declaration. UPPC_FriendDeclaration, /// A declaration qualifier. UPPC_DeclarationQualifier, /// An initializer. UPPC_Initializer, /// A default argument. UPPC_DefaultArgument, /// The type of a non-type template parameter. UPPC_NonTypeTemplateParameterType, /// The type of an exception. UPPC_ExceptionType, /// Partial specialization. UPPC_PartialSpecialization, /// Microsoft __if_exists. UPPC_IfExists, /// Microsoft __if_not_exists. UPPC_IfNotExists, /// Lambda expression. UPPC_Lambda, /// Block expression. UPPC_Block, /// A type constraint. UPPC_TypeConstraint, // A requirement in a requires-expression. UPPC_Requirement, // A requires-clause. UPPC_RequiresClause, }; /// Diagnose unexpanded parameter packs. /// /// \param Loc The location at which we should emit the diagnostic. /// /// \param UPPC The context in which we are diagnosing unexpanded /// parameter packs. /// /// \param Unexpanded the set of unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPacks(SourceLocation Loc, UnexpandedParameterPackContext UPPC, ArrayRef<UnexpandedParameterPack> Unexpanded); /// If the given type contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The source location where a diagnostc should be emitted. /// /// \param T The type that is being checked for unexpanded parameter /// packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC); /// If the given expression contains an unexpanded parameter /// pack, diagnose the error. /// /// \param E The expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(Expr *E, UnexpandedParameterPackContext UPPC = UPPC_Expression); /// If the given requirees-expression contains an unexpanded reference to one /// of its own parameter packs, diagnose the error. /// /// \param RE The requiress-expression that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE); /// If the given nested-name-specifier contains an unexpanded /// parameter pack, diagnose the error. /// /// \param SS The nested-name-specifier that is being checked for /// unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS, UnexpandedParameterPackContext UPPC); /// If the given name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param NameInfo The name (with source location information) that /// is being checked for unexpanded parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo, UnexpandedParameterPackContext UPPC); /// If the given template name contains an unexpanded parameter pack, /// diagnose the error. /// /// \param Loc The location of the template name. /// /// \param Template The template name that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TemplateName Template, UnexpandedParameterPackContext UPPC); /// If the given template argument contains an unexpanded parameter /// pack, diagnose the error. /// /// \param Arg The template argument that is being checked for unexpanded /// parameter packs. /// /// \returns true if an error occurred, false otherwise. bool DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg, UnexpandedParameterPackContext UPPC); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// template argument. /// /// \param Arg The template argument that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TemplateArgumentLoc Arg, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param T The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(QualType T, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// type. /// /// \param TL The type that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(TypeLoc TL, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// nested-name-specifier. /// /// \param NNS The nested-name-specifier that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(NestedNameSpecifierLoc NNS, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Collect the set of unexpanded parameter packs within the given /// name. /// /// \param NameInfo The name that will be traversed to find /// unexpanded parameter packs. void collectUnexpandedParameterPacks(const DeclarationNameInfo &NameInfo, SmallVectorImpl<UnexpandedParameterPack> &Unexpanded); /// Invoked when parsing a template argument followed by an /// ellipsis, which creates a pack expansion. /// /// \param Arg The template argument preceding the ellipsis, which /// may already be invalid. /// /// \param EllipsisLoc The location of the ellipsis. ParsedTemplateArgument ActOnPackExpansion(const ParsedTemplateArgument &Arg, SourceLocation EllipsisLoc); /// Invoked when parsing a type followed by an ellipsis, which /// creates a pack expansion. /// /// \param Type The type preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. TypeResult ActOnPackExpansion(ParsedType Type, SourceLocation EllipsisLoc); /// Construct a pack expansion type from the pattern of the pack /// expansion. TypeSourceInfo *CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Construct a pack expansion type from the pattern of the pack /// expansion. QualType CheckPackExpansion(QualType Pattern, SourceRange PatternRange, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc); /// Invoked when parsing an expression followed by an ellipsis, which /// creates a pack expansion. /// /// \param Pattern The expression preceding the ellipsis, which will become /// the pattern of the pack expansion. /// /// \param EllipsisLoc The location of the ellipsis. ExprResult CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc, Optional<unsigned> NumExpansions); /// Determine whether we could expand a pack expansion with the /// given set of parameter packs into separate arguments by repeatedly /// transforming the pattern. /// /// \param EllipsisLoc The location of the ellipsis that identifies the /// pack expansion. /// /// \param PatternRange The source range that covers the entire pattern of /// the pack expansion. /// /// \param Unexpanded The set of unexpanded parameter packs within the /// pattern. /// /// \param ShouldExpand Will be set to \c true if the transformer should /// expand the corresponding pack expansions into separate arguments. When /// set, \c NumExpansions must also be set. /// /// \param RetainExpansion Whether the caller should add an unexpanded /// pack expansion after all of the expanded arguments. This is used /// when extending explicitly-specified template argument packs per /// C++0x [temp.arg.explicit]p9. /// /// \param NumExpansions The number of separate arguments that will be in /// the expanded form of the corresponding pack expansion. This is both an /// input and an output parameter, which can be set by the caller if the /// number of expansions is known a priori (e.g., due to a prior substitution) /// and will be set by the callee when the number of expansions is known. /// The callee must set this value when \c ShouldExpand is \c true; it may /// set this value in other cases. /// /// \returns true if an error occurred (e.g., because the parameter packs /// are to be instantiated with arguments of different lengths), false /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions) /// must be set. bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef<UnexpandedParameterPack> Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, Optional<unsigned> &NumExpansions); /// Determine the number of arguments in the given pack expansion /// type. /// /// This routine assumes that the number of arguments in the expansion is /// consistent across all of the unexpanded parameter packs in its pattern. /// /// Returns an empty Optional if the type can't be expanded. Optional<unsigned> getNumArgumentsInExpansion(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs); /// Determine whether the given declarator contains any unexpanded /// parameter packs. /// /// This routine is used by the parser to disambiguate function declarators /// with an ellipsis prior to the ')', e.g., /// /// \code /// void f(T...); /// \endcode /// /// To determine whether we have an (unnamed) function parameter pack or /// a variadic function. /// /// \returns true if the declarator contains any unexpanded parameter packs, /// false otherwise. bool containsUnexpandedParameterPacks(Declarator &D); /// Returns the pattern of the pack expansion for a template argument. /// /// \param OrigLoc The template argument to expand. /// /// \param Ellipsis Will be set to the location of the ellipsis. /// /// \param NumExpansions Will be set to the number of expansions that will /// be generated from this pack expansion, if known a priori. TemplateArgumentLoc getTemplateArgumentPackExpansionPattern( TemplateArgumentLoc OrigLoc, SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const; /// Given a template argument that contains an unexpanded parameter pack, but /// which has already been substituted, attempt to determine the number of /// elements that will be produced once this argument is fully-expanded. /// /// This is intended for use when transforming 'sizeof...(Arg)' in order to /// avoid actually expanding the pack where possible. Optional<unsigned> getFullyPackExpandedSize(TemplateArgument Arg); //===--------------------------------------------------------------------===// // C++ Template Argument Deduction (C++ [temp.deduct]) //===--------------------------------------------------------------------===// /// Adjust the type \p ArgFunctionType to match the calling convention, /// noreturn, and optionally the exception specification of \p FunctionType. /// Deduction often wants to ignore these properties when matching function /// types. QualType adjustCCAndNoReturn(QualType ArgFunctionType, QualType FunctionType, bool AdjustExceptionSpec = false); /// Describes the result of template argument deduction. /// /// The TemplateDeductionResult enumeration describes the result of /// template argument deduction, as returned from /// DeduceTemplateArguments(). The separate TemplateDeductionInfo /// structure provides additional information about the results of /// template argument deduction, e.g., the deduced template argument /// list (if successful) or the specific template parameters or /// deduced arguments that were involved in the failure. enum TemplateDeductionResult { /// Template argument deduction was successful. TDK_Success = 0, /// The declaration was invalid; do nothing. TDK_Invalid, /// Template argument deduction exceeded the maximum template /// instantiation depth (which has already been diagnosed). TDK_InstantiationDepth, /// Template argument deduction did not deduce a value /// for every template parameter. TDK_Incomplete, /// Template argument deduction did not deduce a value for every /// expansion of an expanded template parameter pack. TDK_IncompletePack, /// Template argument deduction produced inconsistent /// deduced values for the given template parameter. TDK_Inconsistent, /// Template argument deduction failed due to inconsistent /// cv-qualifiers on a template parameter type that would /// otherwise be deduced, e.g., we tried to deduce T in "const T" /// but were given a non-const "X". TDK_Underqualified, /// Substitution of the deduced template argument values /// resulted in an error. TDK_SubstitutionFailure, /// After substituting deduced template arguments, a dependent /// parameter type did not match the corresponding argument. TDK_DeducedMismatch, /// After substituting deduced template arguments, an element of /// a dependent parameter type did not match the corresponding element /// of the corresponding argument (when deducing from an initializer list). TDK_DeducedMismatchNested, /// A non-depnedent component of the parameter did not match the /// corresponding component of the argument. TDK_NonDeducedMismatch, /// When performing template argument deduction for a function /// template, there were too many call arguments. TDK_TooManyArguments, /// When performing template argument deduction for a function /// template, there were too few call arguments. TDK_TooFewArguments, /// The explicitly-specified template arguments were not valid /// template arguments for the given template. TDK_InvalidExplicitArguments, /// Checking non-dependent argument conversions failed. TDK_NonDependentConversionFailure, /// The deduced arguments did not satisfy the constraints associated /// with the template. TDK_ConstraintsNotSatisfied, /// Deduction failed; that's all we know. TDK_MiscellaneousDeductionFailure, /// CUDA Target attributes do not match. TDK_CUDATargetMismatch }; TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(VarTemplatePartialSpecializationDecl *Partial, const TemplateArgumentList &TemplateArgs, sema::TemplateDeductionInfo &Info); TemplateDeductionResult SubstituteExplicitTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo &ExplicitTemplateArgs, SmallVectorImpl<DeducedTemplateArgument> &Deduced, SmallVectorImpl<QualType> &ParamTypes, QualType *FunctionType, sema::TemplateDeductionInfo &Info); /// brief A function argument from which we performed template argument // deduction for a call. struct OriginalCallArg { OriginalCallArg(QualType OriginalParamType, bool DecomposedParam, unsigned ArgIdx, QualType OriginalArgType) : OriginalParamType(OriginalParamType), DecomposedParam(DecomposedParam), ArgIdx(ArgIdx), OriginalArgType(OriginalArgType) {} QualType OriginalParamType; bool DecomposedParam; unsigned ArgIdx; QualType OriginalArgType; }; TemplateDeductionResult FinishTemplateArgumentDeduction( FunctionTemplateDecl *FunctionTemplate, SmallVectorImpl<DeducedTemplateArgument> &Deduced, unsigned NumExplicitlySpecified, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, SmallVectorImpl<OriginalCallArg> const *OriginalCallArgs = nullptr, bool PartialOverloading = false, llvm::function_ref<bool()> CheckNonDependent = []{ return false; }); TemplateDeductionResult DeduceTemplateArguments( FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool PartialOverloading, llvm::function_ref<bool(ArrayRef<QualType>)> CheckNonDependent); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, QualType ArgFunctionType, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, QualType ToType, CXXConversionDecl *&Specialization, sema::TemplateDeductionInfo &Info); TemplateDeductionResult DeduceTemplateArguments(FunctionTemplateDecl *FunctionTemplate, TemplateArgumentListInfo *ExplicitTemplateArgs, FunctionDecl *&Specialization, sema::TemplateDeductionInfo &Info, bool IsAddressOfFunction = false); /// Substitute Replacement for \p auto in \p TypeWithAuto QualType SubstAutoType(QualType TypeWithAuto, QualType Replacement); /// Substitute Replacement for auto in TypeWithAuto TypeSourceInfo* SubstAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); // Substitute auto in TypeWithAuto for a Dependent auto type QualType SubstAutoTypeDependent(QualType TypeWithAuto); // Substitute auto in TypeWithAuto for a Dependent auto type TypeSourceInfo * SubstAutoTypeSourceInfoDependent(TypeSourceInfo *TypeWithAuto); /// Completely replace the \c auto in \p TypeWithAuto by /// \p Replacement. This does not retain any \c auto type sugar. QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement); TypeSourceInfo *ReplaceAutoTypeSourceInfo(TypeSourceInfo *TypeWithAuto, QualType Replacement); /// Result type of DeduceAutoType. enum DeduceAutoResult { DAR_Succeeded, DAR_Failed, DAR_FailedAlreadyDiagnosed }; DeduceAutoResult DeduceAutoType(TypeSourceInfo *AutoType, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); DeduceAutoResult DeduceAutoType(TypeLoc AutoTypeLoc, Expr *&Initializer, QualType &Result, Optional<unsigned> DependentDeductionDepth = None, bool IgnoreConstraints = false); void DiagnoseAutoDeductionFailure(VarDecl *VDecl, Expr *Init); bool DeduceReturnType(FunctionDecl *FD, SourceLocation Loc, bool Diagnose = true); /// Declare implicit deduction guides for a class template if we've /// not already done so. void DeclareImplicitDeductionGuides(TemplateDecl *Template, SourceLocation Loc); QualType DeduceTemplateSpecializationFromInitializer( TypeSourceInfo *TInfo, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Init); QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init); TypeLoc getReturnTypeLoc(FunctionDecl *FD) const; bool DeduceFunctionTypeFromReturnExpr(FunctionDecl *FD, SourceLocation ReturnLoc, Expr *&RetExpr, AutoType *AT); FunctionTemplateDecl *getMoreSpecializedTemplate( FunctionTemplateDecl *FT1, FunctionTemplateDecl *FT2, SourceLocation Loc, TemplatePartialOrderingContext TPOC, unsigned NumCallArguments1, unsigned NumCallArguments2, bool Reversed = false); UnresolvedSetIterator getMostSpecialized(UnresolvedSetIterator SBegin, UnresolvedSetIterator SEnd, TemplateSpecCandidateSet &FailedCandidates, SourceLocation Loc, const PartialDiagnostic &NoneDiag, const PartialDiagnostic &AmbigDiag, const PartialDiagnostic &CandidateDiag, bool Complain = true, QualType TargetType = QualType()); ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization( ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(ClassTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); VarTemplatePartialSpecializationDecl *getMoreSpecializedPartialSpecialization( VarTemplatePartialSpecializationDecl *PS1, VarTemplatePartialSpecializationDecl *PS2, SourceLocation Loc); bool isMoreSpecializedThanPrimary(VarTemplatePartialSpecializationDecl *T, sema::TemplateDeductionInfo &Info); bool isTemplateTemplateParameterAtLeastAsSpecializedAs( TemplateParameterList *PParam, TemplateDecl *AArg, SourceLocation Loc); void MarkUsedTemplateParameters(const Expr *E, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkUsedTemplateParameters(const TemplateArgumentList &TemplateArgs, bool OnlyDeduced, unsigned Depth, llvm::SmallBitVector &Used); void MarkDeducedTemplateParameters( const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced) { return MarkDeducedTemplateParameters(Context, FunctionTemplate, Deduced); } static void MarkDeducedTemplateParameters(ASTContext &Ctx, const FunctionTemplateDecl *FunctionTemplate, llvm::SmallBitVector &Deduced); //===--------------------------------------------------------------------===// // C++ Template Instantiation // MultiLevelTemplateArgumentList getTemplateInstantiationArgs(NamedDecl *D, const TemplateArgumentList *Innermost = nullptr, bool RelativeToPrimary = false, const FunctionDecl *Pattern = nullptr); /// A context in which code is being synthesized (where a source location /// alone is not sufficient to identify the context). This covers template /// instantiation and various forms of implicitly-generated functions. struct CodeSynthesisContext { /// The kind of template instantiation we are performing enum SynthesisKind { /// We are instantiating a template declaration. The entity is /// the declaration we're instantiating (e.g., a CXXRecordDecl). TemplateInstantiation, /// We are instantiating a default argument for a template /// parameter. The Entity is the template parameter whose argument is /// being instantiated, the Template is the template, and the /// TemplateArgs/NumTemplateArguments provide the template arguments as /// specified. DefaultTemplateArgumentInstantiation, /// We are instantiating a default argument for a function. /// The Entity is the ParmVarDecl, and TemplateArgs/NumTemplateArgs /// provides the template arguments as specified. DefaultFunctionArgumentInstantiation, /// We are substituting explicit template arguments provided for /// a function template. The entity is a FunctionTemplateDecl. ExplicitTemplateArgumentSubstitution, /// We are substituting template argument determined as part of /// template argument deduction for either a class template /// partial specialization or a function template. The /// Entity is either a {Class|Var}TemplatePartialSpecializationDecl or /// a TemplateDecl. DeducedTemplateArgumentSubstitution, /// We are substituting prior template arguments into a new /// template parameter. The template parameter itself is either a /// NonTypeTemplateParmDecl or a TemplateTemplateParmDecl. PriorTemplateArgumentSubstitution, /// We are checking the validity of a default template argument that /// has been used when naming a template-id. DefaultTemplateArgumentChecking, /// We are computing the exception specification for a defaulted special /// member function. ExceptionSpecEvaluation, /// We are instantiating the exception specification for a function /// template which was deferred until it was needed. ExceptionSpecInstantiation, /// We are instantiating a requirement of a requires expression. RequirementInstantiation, /// We are checking the satisfaction of a nested requirement of a requires /// expression. NestedRequirementConstraintsCheck, /// We are declaring an implicit special member function. DeclaringSpecialMember, /// We are declaring an implicit 'operator==' for a defaulted /// 'operator<=>'. DeclaringImplicitEqualityComparison, /// We are defining a synthesized function (such as a defaulted special /// member). DefiningSynthesizedFunction, // We are checking the constraints associated with a constrained entity or // the constraint expression of a concept. This includes the checks that // atomic constraints have the type 'bool' and that they can be constant // evaluated. ConstraintsCheck, // We are substituting template arguments into a constraint expression. ConstraintSubstitution, // We are normalizing a constraint expression. ConstraintNormalization, // We are substituting into the parameter mapping of an atomic constraint // during normalization. ParameterMappingSubstitution, /// We are rewriting a comparison operator in terms of an operator<=>. RewritingOperatorAsSpaceship, /// We are initializing a structured binding. InitializingStructuredBinding, /// We are marking a class as __dllexport. MarkingClassDllexported, /// Added for Template instantiation observation. /// Memoization means we are _not_ instantiating a template because /// it is already instantiated (but we entered a context where we /// would have had to if it was not already instantiated). Memoization } Kind; /// Was the enclosing context a non-instantiation SFINAE context? bool SavedInNonInstantiationSFINAEContext; /// The point of instantiation or synthesis within the source code. SourceLocation PointOfInstantiation; /// The entity that is being synthesized. Decl *Entity; /// The template (or partial specialization) in which we are /// performing the instantiation, for substitutions of prior template /// arguments. NamedDecl *Template; /// The list of template arguments we are substituting, if they /// are not part of the entity. const TemplateArgument *TemplateArgs; // FIXME: Wrap this union around more members, or perhaps store the // kind-specific members in the RAII object owning the context. union { /// The number of template arguments in TemplateArgs. unsigned NumTemplateArgs; /// The special member being declared or defined. CXXSpecialMember SpecialMember; }; ArrayRef<TemplateArgument> template_arguments() const { assert(Kind != DeclaringSpecialMember); return {TemplateArgs, NumTemplateArgs}; } /// The template deduction info object associated with the /// substitution or checking of explicit or deduced template arguments. sema::TemplateDeductionInfo *DeductionInfo; /// The source range that covers the construct that cause /// the instantiation, e.g., the template-id that causes a class /// template instantiation. SourceRange InstantiationRange; CodeSynthesisContext() : Kind(TemplateInstantiation), SavedInNonInstantiationSFINAEContext(false), Entity(nullptr), Template(nullptr), TemplateArgs(nullptr), NumTemplateArgs(0), DeductionInfo(nullptr) {} /// Determines whether this template is an actual instantiation /// that should be counted toward the maximum instantiation depth. bool isInstantiationRecord() const; }; /// List of active code synthesis contexts. /// /// This vector is treated as a stack. As synthesis of one entity requires /// synthesis of another, additional contexts are pushed onto the stack. SmallVector<CodeSynthesisContext, 16> CodeSynthesisContexts; /// Specializations whose definitions are currently being instantiated. llvm::DenseSet<std::pair<Decl *, unsigned>> InstantiatingSpecializations; /// Non-dependent types used in templates that have already been instantiated /// by some template instantiation. llvm::DenseSet<QualType> InstantiatedNonDependentTypes; /// Extra modules inspected when performing a lookup during a template /// instantiation. Computed lazily. SmallVector<Module*, 16> CodeSynthesisContextLookupModules; /// Cache of additional modules that should be used for name lookup /// within the current template instantiation. Computed lazily; use /// getLookupModules() to get a complete set. llvm::DenseSet<Module*> LookupModulesCache; /// Get the set of additional modules that should be checked during /// name lookup. A module and its imports become visible when instanting a /// template defined within it. llvm::DenseSet<Module*> &getLookupModules(); /// Map from the most recent declaration of a namespace to the most /// recent visible declaration of that namespace. llvm::DenseMap<NamedDecl*, NamedDecl*> VisibleNamespaceCache; /// Whether we are in a SFINAE context that is not associated with /// template instantiation. /// /// This is used when setting up a SFINAE trap (\c see SFINAETrap) outside /// of a template instantiation or template argument deduction. bool InNonInstantiationSFINAEContext; /// The number of \p CodeSynthesisContexts that are not template /// instantiations and, therefore, should not be counted as part of the /// instantiation depth. /// /// When the instantiation depth reaches the user-configurable limit /// \p LangOptions::InstantiationDepth we will abort instantiation. // FIXME: Should we have a similar limit for other forms of synthesis? unsigned NonInstantiationEntries; /// The depth of the context stack at the point when the most recent /// error or warning was produced. /// /// This value is used to suppress printing of redundant context stacks /// when there are multiple errors or warnings in the same instantiation. // FIXME: Does this belong in Sema? It's tough to implement it anywhere else. unsigned LastEmittedCodeSynthesisContextDepth = 0; /// The template instantiation callbacks to trace or track /// instantiations (objects can be chained). /// /// This callbacks is used to print, trace or track template /// instantiations as they are being constructed. std::vector<std::unique_ptr<TemplateInstantiationCallback>> TemplateInstCallbacks; /// The current index into pack expansion arguments that will be /// used for substitution of parameter packs. /// /// The pack expansion index will be -1 to indicate that parameter packs /// should be instantiated as themselves. Otherwise, the index specifies /// which argument within the parameter pack will be used for substitution. int ArgumentPackSubstitutionIndex; /// RAII object used to change the argument pack substitution index /// within a \c Sema object. /// /// See \c ArgumentPackSubstitutionIndex for more information. class ArgumentPackSubstitutionIndexRAII { Sema &Self; int OldSubstitutionIndex; public: ArgumentPackSubstitutionIndexRAII(Sema &Self, int NewSubstitutionIndex) : Self(Self), OldSubstitutionIndex(Self.ArgumentPackSubstitutionIndex) { Self.ArgumentPackSubstitutionIndex = NewSubstitutionIndex; } ~ArgumentPackSubstitutionIndexRAII() { Self.ArgumentPackSubstitutionIndex = OldSubstitutionIndex; } }; friend class ArgumentPackSubstitutionRAII; /// For each declaration that involved template argument deduction, the /// set of diagnostics that were suppressed during that template argument /// deduction. /// /// FIXME: Serialize this structure to the AST file. typedef llvm::DenseMap<Decl *, SmallVector<PartialDiagnosticAt, 1> > SuppressedDiagnosticsMap; SuppressedDiagnosticsMap SuppressedDiagnostics; /// A stack object to be created when performing template /// instantiation. /// /// Construction of an object of type \c InstantiatingTemplate /// pushes the current instantiation onto the stack of active /// instantiations. If the size of this stack exceeds the maximum /// number of recursive template instantiations, construction /// produces an error and evaluates true. /// /// Destruction of this object will pop the named instantiation off /// the stack. struct InstantiatingTemplate { /// Note that we are instantiating a class template, /// function template, variable template, alias template, /// or a member thereof. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange = SourceRange()); struct ExceptionSpecification {}; /// Note that we are instantiating an exception specification /// of a function template. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity, ExceptionSpecification, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument in a /// template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting either explicitly-specified or /// deduced template arguments during function template argument deduction. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionTemplateDecl *FunctionTemplate, ArrayRef<TemplateArgument> TemplateArgs, CodeSynthesisContext::SynthesisKind Kind, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template declaration. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a class template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ClassTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating as part of template /// argument deduction for a variable template partial /// specialization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, VarTemplatePartialSpecializationDecl *PartialSpec, ArrayRef<TemplateArgument> TemplateArgs, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// Note that we are instantiating a default argument for a function /// parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange = SourceRange()); /// Note that we are substituting prior template arguments into a /// non-type parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are substituting prior template arguments into a /// template template parameter. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template, TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); /// Note that we are checking the default template argument /// against the template parameter for a given template-id. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template, NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintsCheck {}; /// \brief Note that we are checking the constraints associated with some /// constrained entity (a concept declaration or a template with associated /// constraints). InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintsCheck, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange); struct ConstraintSubstitution {}; /// \brief Note that we are checking a constraint expression associated /// with a template declaration or as part of the satisfaction check of a /// concept. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintSubstitution, NamedDecl *Template, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange); struct ConstraintNormalization {}; /// \brief Note that we are normalizing a constraint expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ConstraintNormalization, NamedDecl *Template, SourceRange InstantiationRange); struct ParameterMappingSubstitution {}; /// \brief Note that we are subtituting into the parameter mapping of an /// atomic constraint during constraint normalization. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, ParameterMappingSubstitution, NamedDecl *Template, SourceRange InstantiationRange); /// \brief Note that we are substituting template arguments into a part of /// a requirement of a requires expression. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange = SourceRange()); /// \brief Note that we are checking the satisfaction of the constraint /// expression inside of a nested requirement. InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, concepts::NestedRequirement *Req, ConstraintsCheck, SourceRange InstantiationRange = SourceRange()); /// Note that we have finished instantiating this template. void Clear(); ~InstantiatingTemplate() { Clear(); } /// Determines whether we have exceeded the maximum /// recursive template instantiations. bool isInvalid() const { return Invalid; } /// Determine whether we are already instantiating this /// specialization in some surrounding active instantiation. bool isAlreadyInstantiating() const { return AlreadyInstantiating; } private: Sema &SemaRef; bool Invalid; bool AlreadyInstantiating; bool CheckInstantiationDepth(SourceLocation PointOfInstantiation, SourceRange InstantiationRange); InstantiatingTemplate( Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind, SourceLocation PointOfInstantiation, SourceRange InstantiationRange, Decl *Entity, NamedDecl *Template = nullptr, ArrayRef<TemplateArgument> TemplateArgs = None, sema::TemplateDeductionInfo *DeductionInfo = nullptr); InstantiatingTemplate(const InstantiatingTemplate&) = delete; InstantiatingTemplate& operator=(const InstantiatingTemplate&) = delete; }; void pushCodeSynthesisContext(CodeSynthesisContext Ctx); void popCodeSynthesisContext(); /// Determine whether we are currently performing template instantiation. bool inTemplateInstantiation() const { return CodeSynthesisContexts.size() > NonInstantiationEntries; } void PrintContextStack() { if (!CodeSynthesisContexts.empty() && CodeSynthesisContexts.size() != LastEmittedCodeSynthesisContextDepth) { PrintInstantiationStack(); LastEmittedCodeSynthesisContextDepth = CodeSynthesisContexts.size(); } if (PragmaAttributeCurrentTargetDecl) PrintPragmaAttributeInstantiationPoint(); } void PrintInstantiationStack(); void PrintPragmaAttributeInstantiationPoint(); /// Determines whether we are currently in a context where /// template argument substitution failures are not considered /// errors. /// /// \returns An empty \c Optional if we're not in a SFINAE context. /// Otherwise, contains a pointer that, if non-NULL, contains the nearest /// template-deduction context object, which can be used to capture /// diagnostics that will be suppressed. Optional<sema::TemplateDeductionInfo *> isSFINAEContext() const; /// Determines whether we are currently in a context that /// is not evaluated as per C++ [expr] p5. bool isUnevaluatedContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isUnevaluated(); } bool isImmediateFunctionContext() const { assert(!ExprEvalContexts.empty() && "Must be in an expression evaluation context"); return ExprEvalContexts.back().isImmediateFunctionContext(); } /// RAII class used to determine whether SFINAE has /// trapped any errors that occur during template argument /// deduction. class SFINAETrap { Sema &SemaRef; unsigned PrevSFINAEErrors; bool PrevInNonInstantiationSFINAEContext; bool PrevAccessCheckingSFINAE; bool PrevLastDiagnosticIgnored; public: explicit SFINAETrap(Sema &SemaRef, bool AccessCheckingSFINAE = false) : SemaRef(SemaRef), PrevSFINAEErrors(SemaRef.NumSFINAEErrors), PrevInNonInstantiationSFINAEContext( SemaRef.InNonInstantiationSFINAEContext), PrevAccessCheckingSFINAE(SemaRef.AccessCheckingSFINAE), PrevLastDiagnosticIgnored( SemaRef.getDiagnostics().isLastDiagnosticIgnored()) { if (!SemaRef.isSFINAEContext()) SemaRef.InNonInstantiationSFINAEContext = true; SemaRef.AccessCheckingSFINAE = AccessCheckingSFINAE; } ~SFINAETrap() { SemaRef.NumSFINAEErrors = PrevSFINAEErrors; SemaRef.InNonInstantiationSFINAEContext = PrevInNonInstantiationSFINAEContext; SemaRef.AccessCheckingSFINAE = PrevAccessCheckingSFINAE; SemaRef.getDiagnostics().setLastDiagnosticIgnored( PrevLastDiagnosticIgnored); } /// Determine whether any SFINAE errors have been trapped. bool hasErrorOccurred() const { return SemaRef.NumSFINAEErrors > PrevSFINAEErrors; } }; /// RAII class used to indicate that we are performing provisional /// semantic analysis to determine the validity of a construct, so /// typo-correction and diagnostics in the immediate context (not within /// implicitly-instantiated templates) should be suppressed. class TentativeAnalysisScope { Sema &SemaRef; // FIXME: Using a SFINAETrap for this is a hack. SFINAETrap Trap; bool PrevDisableTypoCorrection; public: explicit TentativeAnalysisScope(Sema &SemaRef) : SemaRef(SemaRef), Trap(SemaRef, true), PrevDisableTypoCorrection(SemaRef.DisableTypoCorrection) { SemaRef.DisableTypoCorrection = true; } ~TentativeAnalysisScope() { SemaRef.DisableTypoCorrection = PrevDisableTypoCorrection; } }; /// The current instantiation scope used to store local /// variables. LocalInstantiationScope *CurrentInstantiationScope; /// Tracks whether we are in a context where typo correction is /// disabled. bool DisableTypoCorrection; /// The number of typos corrected by CorrectTypo. unsigned TyposCorrected; typedef llvm::SmallSet<SourceLocation, 2> SrcLocSet; typedef llvm::DenseMap<IdentifierInfo *, SrcLocSet> IdentifierSourceLocations; /// A cache containing identifiers for which typo correction failed and /// their locations, so that repeated attempts to correct an identifier in a /// given location are ignored if typo correction already failed for it. IdentifierSourceLocations TypoCorrectionFailures; /// Worker object for performing CFG-based warnings. sema::AnalysisBasedWarnings AnalysisWarnings; threadSafety::BeforeSet *ThreadSafetyDeclCache; /// An entity for which implicit template instantiation is required. /// /// The source location associated with the declaration is the first place in /// the source code where the declaration was "used". It is not necessarily /// the point of instantiation (which will be either before or after the /// namespace-scope declaration that triggered this implicit instantiation), /// However, it is the location that diagnostics should generally refer to, /// because users will need to know what code triggered the instantiation. typedef std::pair<ValueDecl *, SourceLocation> PendingImplicitInstantiation; /// The queue of implicit template instantiations that are required /// but have not yet been performed. std::deque<PendingImplicitInstantiation> PendingInstantiations; /// Queue of implicit template instantiations that cannot be performed /// eagerly. SmallVector<PendingImplicitInstantiation, 1> LateParsedInstantiations; class GlobalEagerInstantiationScope { public: GlobalEagerInstantiationScope(Sema &S, bool Enabled) : S(S), Enabled(Enabled) { if (!Enabled) return; SavedPendingInstantiations.swap(S.PendingInstantiations); SavedVTableUses.swap(S.VTableUses); } void perform() { if (Enabled) { S.DefineUsedVTables(); S.PerformPendingInstantiations(); } } ~GlobalEagerInstantiationScope() { if (!Enabled) return; // Restore the set of pending vtables. assert(S.VTableUses.empty() && "VTableUses should be empty before it is discarded."); S.VTableUses.swap(SavedVTableUses); // Restore the set of pending implicit instantiations. if (S.TUKind != TU_Prefix || !S.LangOpts.PCHInstantiateTemplates) { assert(S.PendingInstantiations.empty() && "PendingInstantiations should be empty before it is discarded."); S.PendingInstantiations.swap(SavedPendingInstantiations); } else { // Template instantiations in the PCH may be delayed until the TU. S.PendingInstantiations.swap(SavedPendingInstantiations); S.PendingInstantiations.insert(S.PendingInstantiations.end(), SavedPendingInstantiations.begin(), SavedPendingInstantiations.end()); } } private: Sema &S; SmallVector<VTableUse, 16> SavedVTableUses; std::deque<PendingImplicitInstantiation> SavedPendingInstantiations; bool Enabled; }; /// The queue of implicit template instantiations that are required /// and must be performed within the current local scope. /// /// This queue is only used for member functions of local classes in /// templates, which must be instantiated in the same scope as their /// enclosing function, so that they can reference function-local /// types, static variables, enumerators, etc. std::deque<PendingImplicitInstantiation> PendingLocalImplicitInstantiations; class LocalEagerInstantiationScope { public: LocalEagerInstantiationScope(Sema &S) : S(S) { SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } void perform() { S.PerformPendingInstantiations(/*LocalOnly=*/true); } ~LocalEagerInstantiationScope() { assert(S.PendingLocalImplicitInstantiations.empty() && "there shouldn't be any pending local implicit instantiations"); SavedPendingLocalImplicitInstantiations.swap( S.PendingLocalImplicitInstantiations); } private: Sema &S; std::deque<PendingImplicitInstantiation> SavedPendingLocalImplicitInstantiations; }; /// A helper class for building up ExtParameterInfos. class ExtParameterInfoBuilder { SmallVector<FunctionProtoType::ExtParameterInfo, 16> Infos; bool HasInteresting = false; public: /// Set the ExtParameterInfo for the parameter at the given index, /// void set(unsigned index, FunctionProtoType::ExtParameterInfo info) { assert(Infos.size() <= index); Infos.resize(index); Infos.push_back(info); if (!HasInteresting) HasInteresting = (info != FunctionProtoType::ExtParameterInfo()); } /// Return a pointer (suitable for setting in an ExtProtoInfo) to the /// ExtParameterInfo array we've built up. const FunctionProtoType::ExtParameterInfo * getPointerOrNull(unsigned numParams) { if (!HasInteresting) return nullptr; Infos.resize(numParams); return Infos.data(); } }; void PerformPendingInstantiations(bool LocalOnly = false); TypeSourceInfo *SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST = false); QualType SubstType(QualType T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstType(TypeLoc TL, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity); TypeSourceInfo *SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals); void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args); bool SubstExceptionSpec(SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI, SmallVectorImpl<QualType> &ExceptionStorage, const MultiLevelTemplateArgumentList &Args); ParmVarDecl *SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, Optional<unsigned> NumExpansions, bool ExpectParameterPack); bool SubstParmTypes(SourceLocation Loc, ArrayRef<ParmVarDecl *> Params, const FunctionProtoType::ExtParameterInfo *ExtParamInfos, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<QualType> &ParamTypes, SmallVectorImpl<ParmVarDecl *> *OutParams, ExtParameterInfoBuilder &ParamInfos); ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the given template arguments into a list of /// expressions, expanding pack expansions if required. /// /// \param Exprs The list of expressions to substitute into. /// /// \param IsCall Whether this is some form of call, in which case /// default arguments will be dropped. /// /// \param TemplateArgs The set of template arguments to substitute. /// /// \param Outputs Will receive all of the substituted arguments. /// /// \returns true if an error occurred, false otherwise. bool SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl<Expr *> &Outputs); StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateParameterList * SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs); Decl *SubstDecl(Decl *D, DeclContext *Owner, const MultiLevelTemplateArgumentList &TemplateArgs); /// Substitute the name and return type of a defaulted 'operator<=>' to form /// an implicit 'operator=='. FunctionDecl *SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD, FunctionDecl *Spaceship); ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit); bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain = true); bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); bool InstantiateInClassInitializer( SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs); struct LateInstantiatedAttribute { const Attr *TmplAttr; LocalInstantiationScope *Scope; Decl *NewDecl; LateInstantiatedAttribute(const Attr *A, LocalInstantiationScope *S, Decl *D) : TmplAttr(A), Scope(S), NewDecl(D) { } }; typedef SmallVector<LateInstantiatedAttribute, 16> LateInstantiatedAttrVec; void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateAttrsForDecl(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *OuterMostScope = nullptr); void InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor); bool usesPartialOrExplicitSpecialization( SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec); bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain = true); void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK); void InstantiateClassTemplateSpecializationMembers( SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK); NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs); DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs); TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs); bool SubstTypeConstraint(TemplateTypeParmDecl *Inst, const TypeConstraint *TC, const MultiLevelTemplateArgumentList &TemplateArgs); bool InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param); void InstantiateExceptionSpec(SourceLocation PointOfInstantiation, FunctionDecl *Function); bool CheckInstantiatedFunctionTemplateConstraints( SourceLocation PointOfInstantiation, FunctionDecl *Decl, ArrayRef<TemplateArgument> TemplateArgs, ConstraintSatisfaction &Satisfaction); FunctionDecl *InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD, const TemplateArgumentList *Args, SourceLocation Loc); void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); VarTemplateSpecializationDecl *BuildVarTemplateInstantiation( VarTemplateDecl *VarTemplate, VarDecl *FromVar, const TemplateArgumentList &TemplateArgList, const TemplateArgumentListInfo &TemplateArgsInfo, SmallVectorImpl<TemplateArgument> &Converted, SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs = nullptr, LocalInstantiationScope *StartingScope = nullptr); VarTemplateSpecializationDecl *CompleteVarTemplateSpecializationDecl( VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl, const MultiLevelTemplateArgumentList &TemplateArgs); void BuildVariableInstantiation(VarDecl *NewVar, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs, LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner, LocalInstantiationScope *StartingScope, bool InstantiatingVarTemplate = false, VarTemplateSpecializationDecl *PrevVTSD = nullptr); void InstantiateVariableInitializer( VarDecl *Var, VarDecl *OldVar, const MultiLevelTemplateArgumentList &TemplateArgs); void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive = false, bool DefinitionRequired = false, bool AtEndOfTU = false); void InstantiateMemInitializers(CXXConstructorDecl *New, const CXXConstructorDecl *Tmpl, const MultiLevelTemplateArgumentList &TemplateArgs); NamedDecl *FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext = false); DeclContext *FindInstantiatedContext(SourceLocation Loc, DeclContext *DC, const MultiLevelTemplateArgumentList &TemplateArgs); // Objective-C declarations. enum ObjCContainerKind { OCK_None = -1, OCK_Interface = 0, OCK_Protocol, OCK_Category, OCK_ClassExtension, OCK_Implementation, OCK_CategoryImplementation }; ObjCContainerKind getObjCContainerKind() const; DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound); ObjCTypeParamList *actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef<Decl *> typeParams, SourceLocation rAngleLoc); void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList); Decl *ActOnStartClassInterface( Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange); void ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs, SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName, SourceLocation SuperLoc); Decl *ActOnCompatibilityAlias( SourceLocation AtCompatibilityAliasLoc, IdentifierInfo *AliasName, SourceLocation AliasLocation, IdentifierInfo *ClassName, SourceLocation ClassLocation); bool CheckForwardProtocolDeclarationForCircularDependency( IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList<ObjCProtocolDecl> &PList); Decl *ActOnStartProtocolInterface( SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryInterface( SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList); Decl *ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList); DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls); DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists, unsigned NumElts); DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef<IdentifierLocPair> IdentList, const ParsedAttributesView &attrList); void FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer, ArrayRef<IdentifierLocPair> ProtocolId, SmallVectorImpl<Decl *> &Protocols); void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst = false); /// Given a list of identifiers (and their locations), resolve the /// names to either Objective-C protocol qualifiers or type /// arguments, as appropriate. void actOnObjCTypeArgsOrProtocolQualifiers( Scope *S, ParsedType baseType, SourceLocation lAngleLoc, ArrayRef<IdentifierInfo *> identifiers, ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc, bool warnOnIncompleteProtocols); /// Build a an Objective-C protocol-qualified 'id' type where no /// base type was specified. TypeResult actOnObjCProtocolQualifierType( SourceLocation lAngleLoc, ArrayRef<Decl *> protocols, ArrayRef<SourceLocation> protocolLocs, SourceLocation rAngleLoc); /// Build a specialized and/or protocol-qualified Objective-C type. TypeResult actOnObjCTypeArgsAndProtocolQualifiers( Scope *S, SourceLocation Loc, ParsedType BaseType, SourceLocation TypeArgsLAngleLoc, ArrayRef<ParsedType> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<Decl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc); /// Build an Objective-C type parameter type. QualType BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Build an Objective-C object pointer type. QualType BuildObjCObjectType(QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc, ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc, SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols, ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc, bool FailOnError = false); /// Ensure attributes are consistent with type. /// \param [in, out] Attributes The attributes to check; they will /// be modified to be consistent with \p PropertyTy. void CheckObjCPropertyAttributes(Decl *PropertyPtrTy, SourceLocation Loc, unsigned &Attributes, bool propertyInPrimaryClass); /// Process the specified property declaration and create decls for the /// setters and getters as needed. /// \param property The property declaration being processed void ProcessPropertyDecl(ObjCPropertyDecl *property); void DiagnosePropertyMismatch(ObjCPropertyDecl *Property, ObjCPropertyDecl *SuperProperty, const IdentifierInfo *Name, bool OverridingProtocolProperty); void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID); Decl *ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods = None, ArrayRef<DeclGroupPtrTy> allTUVars = None); Decl *ActOnProperty(Scope *S, SourceLocation AtLoc, SourceLocation LParenLoc, FieldDeclarator &FD, ObjCDeclSpec &ODS, Selector GetterSel, Selector SetterSel, tok::ObjCKeywordKind MethodImplKind, DeclContext *lexicalDC = nullptr); Decl *ActOnPropertyImplDecl(Scope *S, SourceLocation AtLoc, SourceLocation PropertyLoc, bool ImplKind, IdentifierInfo *PropertyId, IdentifierInfo *PropertyIvar, SourceLocation PropertyIvarLoc, ObjCPropertyQueryKind QueryKind); enum ObjCSpecialMethodKind { OSMK_None, OSMK_Alloc, OSMK_New, OSMK_Copy, OSMK_RetainingInit, OSMK_NonRetainingInit }; struct ObjCArgInfo { IdentifierInfo *Name; SourceLocation NameLoc; // The Type is null if no type was specified, and the DeclSpec is invalid // in this case. ParsedType Type; ObjCDeclSpec DeclSpec; /// ArgAttrs - Attribute list for this argument. ParsedAttributesView ArgAttrs; }; Decl *ActOnMethodDeclaration( Scope *S, SourceLocation BeginLoc, // location of the + or -. SourceLocation EndLoc, // location of the ; or {. tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType, ArrayRef<SourceLocation> SelectorLocs, Selector Sel, // optional arguments. The number of types/arguments is obtained // from the Sel.getNumArgs(). ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodImplKind, bool isVariadic, bool MethodDefinition); ObjCMethodDecl *LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool IsInstance); ObjCMethodDecl *LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance); bool CheckARCMethodDecl(ObjCMethodDecl *method); bool inferObjCARCLifetime(ValueDecl *decl); void deduceOpenCLAddressSpace(ValueDecl *decl); ExprResult HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super); ExprResult ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc); ObjCMethodDecl *tryCaptureObjCSelf(SourceLocation Loc); /// Describes the kind of message expression indicated by a message /// send that starts with an identifier. enum ObjCMessageKind { /// The message is sent to 'super'. ObjCSuperMessage, /// The message is an instance message. ObjCInstanceMessage, /// The message is a class message, and the identifier is a type /// name. ObjCClassMessage }; ObjCMessageKind getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType); ExprResult ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args, bool isImplicit = false); ExprResult BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args); ExprResult ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args); ExprResult BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr); ExprResult ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr); void CheckTollFreeBridgeCast(QualType castType, Expr *castExpr); void CheckObjCBridgeRelatedCast(QualType castType, Expr *castExpr); bool CheckTollFreeBridgeStaticCast(QualType castType, Expr *castExpr, CastKind &Kind); bool checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs, bool Diagnose = true); bool CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr, bool Diagnose = true); bool CheckConversionToObjCLiteral(QualType DstType, Expr *&SrcExpr, bool Diagnose = true); bool checkInitMethod(ObjCMethodDecl *method, QualType receiverTypeIfCall); /// Check whether the given new method is a valid override of the /// given overridden method, and set any properties that should be inherited. void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden); /// Describes the compatibility of a result type with its method. enum ResultTypeCompatibilityKind { RTC_Compatible, RTC_Incompatible, RTC_Unknown }; void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden); void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC); enum PragmaOptionsAlignKind { POAK_Native, // #pragma options align=native POAK_Natural, // #pragma options align=natural POAK_Packed, // #pragma options align=packed POAK_Power, // #pragma options align=power POAK_Mac68k, // #pragma options align=mac68k POAK_Reset // #pragma options align=reset }; /// ActOnPragmaClangSection - Called on well formed \#pragma clang section void ActOnPragmaClangSection(SourceLocation PragmaLoc, PragmaClangSectionAction Action, PragmaClangSectionKind SecKind, StringRef SecName); /// ActOnPragmaOptionsAlign - Called on well formed \#pragma options align. void ActOnPragmaOptionsAlign(PragmaOptionsAlignKind Kind, SourceLocation PragmaLoc); /// ActOnPragmaPack - Called on well formed \#pragma pack(...). void ActOnPragmaPack(SourceLocation PragmaLoc, PragmaMsStackAction Action, StringRef SlotLabel, Expr *Alignment); enum class PragmaAlignPackDiagnoseKind { NonDefaultStateAtInclude, ChangedStateAtExit }; void DiagnoseNonDefaultPragmaAlignPack(PragmaAlignPackDiagnoseKind Kind, SourceLocation IncludeLoc); void DiagnoseUnterminatedPragmaAlignPack(); /// ActOnPragmaMSStruct - Called on well formed \#pragma ms_struct [on|off]. void ActOnPragmaMSStruct(PragmaMSStructKind Kind); /// ActOnPragmaMSComment - Called on well formed /// \#pragma comment(kind, "arg"). void ActOnPragmaMSComment(SourceLocation CommentLoc, PragmaMSCommentKind Kind, StringRef Arg); /// ActOnPragmaMSPointersToMembers - called on well formed \#pragma /// pointers_to_members(representation method[, general purpose /// representation]). void ActOnPragmaMSPointersToMembers( LangOptions::PragmaMSPointersToMembersKind Kind, SourceLocation PragmaLoc); /// Called on well formed \#pragma vtordisp(). void ActOnPragmaMSVtorDisp(PragmaMsStackAction Action, SourceLocation PragmaLoc, MSVtorDispMode Value); enum PragmaSectionKind { PSK_DataSeg, PSK_BSSSeg, PSK_ConstSeg, PSK_CodeSeg, }; bool UnifySection(StringRef SectionName, int SectionFlags, NamedDecl *TheDecl); bool UnifySection(StringRef SectionName, int SectionFlags, SourceLocation PragmaSectionLocation); /// Called on well formed \#pragma bss_seg/data_seg/const_seg/code_seg. void ActOnPragmaMSSeg(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, StringLiteral *SegmentName, llvm::StringRef PragmaName); /// Called on well formed \#pragma section(). void ActOnPragmaMSSection(SourceLocation PragmaLocation, int SectionFlags, StringLiteral *SegmentName); /// Called on well-formed \#pragma init_seg(). void ActOnPragmaMSInitSeg(SourceLocation PragmaLocation, StringLiteral *SegmentName); /// Called on #pragma clang __debug dump II void ActOnPragmaDump(Scope *S, SourceLocation Loc, IdentifierInfo *II); /// ActOnPragmaDetectMismatch - Call on well-formed \#pragma detect_mismatch void ActOnPragmaDetectMismatch(SourceLocation Loc, StringRef Name, StringRef Value); /// Are precise floating point semantics currently enabled? bool isPreciseFPEnabled() { return !CurFPFeatures.getAllowFPReassociate() && !CurFPFeatures.getNoSignedZero() && !CurFPFeatures.getAllowReciprocal() && !CurFPFeatures.getAllowApproxFunc(); } /// ActOnPragmaFloatControl - Call on well-formed \#pragma float_control void ActOnPragmaFloatControl(SourceLocation Loc, PragmaMsStackAction Action, PragmaFloatControlKind Value); /// ActOnPragmaUnused - Called on well-formed '\#pragma unused'. void ActOnPragmaUnused(const Token &Identifier, Scope *curScope, SourceLocation PragmaLoc); /// ActOnPragmaVisibility - Called on well formed \#pragma GCC visibility... . void ActOnPragmaVisibility(const IdentifierInfo* VisType, SourceLocation PragmaLoc); NamedDecl *DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, SourceLocation Loc); void DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W); /// ActOnPragmaWeakID - Called on well formed \#pragma weak ident. void ActOnPragmaWeakID(IdentifierInfo* WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc); /// ActOnPragmaRedefineExtname - Called on well formed /// \#pragma redefine_extname oldname newname. void ActOnPragmaRedefineExtname(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaWeakAlias - Called on well formed \#pragma weak ident = ident. void ActOnPragmaWeakAlias(IdentifierInfo* WeakName, IdentifierInfo* AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc); /// ActOnPragmaFPContract - Called on well formed /// \#pragma {STDC,OPENCL} FP_CONTRACT and /// \#pragma clang fp contract void ActOnPragmaFPContract(SourceLocation Loc, LangOptions::FPModeKind FPC); /// Called on well formed /// \#pragma clang fp reassociate void ActOnPragmaFPReassociate(SourceLocation Loc, bool IsEnabled); /// ActOnPragmaFenvAccess - Called on well formed /// \#pragma STDC FENV_ACCESS void ActOnPragmaFEnvAccess(SourceLocation Loc, bool IsEnabled); /// Called on well formed '\#pragma clang fp' that has option 'exceptions'. void ActOnPragmaFPExceptions(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// Called to set constant rounding mode for floating point operations. void setRoundingMode(SourceLocation Loc, llvm::RoundingMode); /// Called to set exception behavior for floating point operations. void setExceptionMode(SourceLocation Loc, LangOptions::FPExceptionModeKind); /// AddAlignmentAttributesForRecord - Adds any needed alignment attributes to /// a the record decl, to handle '\#pragma pack' and '\#pragma options align'. void AddAlignmentAttributesForRecord(RecordDecl *RD); /// AddMsStructLayoutForRecord - Adds ms_struct layout attribute to record. void AddMsStructLayoutForRecord(RecordDecl *RD); /// PushNamespaceVisibilityAttr - Note that we've entered a /// namespace with a visibility attribute. void PushNamespaceVisibilityAttr(const VisibilityAttr *Attr, SourceLocation Loc); /// AddPushedVisibilityAttribute - If '\#pragma GCC visibility' was used, /// add an appropriate visibility attribute. void AddPushedVisibilityAttribute(Decl *RD); /// PopPragmaVisibility - Pop the top element of the visibility stack; used /// for '\#pragma GCC visibility' and visibility attributes on namespaces. void PopPragmaVisibility(bool IsNamespaceEnd, SourceLocation EndLoc); /// FreeVisContext - Deallocate and null out VisContext. void FreeVisContext(); /// AddCFAuditedAttribute - Check whether we're currently within /// '\#pragma clang arc_cf_code_audited' and, if so, consider adding /// the appropriate attribute. void AddCFAuditedAttribute(Decl *D); void ActOnPragmaAttributeAttribute(ParsedAttr &Attribute, SourceLocation PragmaLoc, attr::ParsedSubjectMatchRuleSet Rules); void ActOnPragmaAttributeEmptyPush(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Called on well-formed '\#pragma clang attribute pop'. void ActOnPragmaAttributePop(SourceLocation PragmaLoc, const IdentifierInfo *Namespace); /// Adds the attributes that have been specified using the /// '\#pragma clang attribute push' directives to the given declaration. void AddPragmaAttributes(Scope *S, Decl *D); void DiagnoseUnterminatedPragmaAttribute(); /// Called on well formed \#pragma clang optimize. void ActOnPragmaOptimize(bool On, SourceLocation PragmaLoc); /// Get the location for the currently active "\#pragma clang optimize /// off". If this location is invalid, then the state of the pragma is "on". SourceLocation getOptimizeOffPragmaLocation() const { return OptimizeOffPragmaLocation; } /// Only called on function definitions; if there is a pragma in scope /// with the effect of a range-based optnone, consider marking the function /// with attribute optnone. void AddRangeBasedOptnone(FunctionDecl *FD); /// Adds the 'optnone' attribute to the function declaration if there /// are no conflicts; Loc represents the location causing the 'optnone' /// attribute to be added (usually because of a pragma). void AddOptnoneAttributeIfNoConflicts(FunctionDecl *FD, SourceLocation Loc); void AddIntelFPGABankBitsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size); template <typename AttrType> void addIntelTripleArgAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr); void AddWorkGroupSizeHintAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDim, Expr *YDim, Expr *ZDim); WorkGroupSizeHintAttr * MergeWorkGroupSizeHintAttr(Decl *D, const WorkGroupSizeHintAttr &A); void AddIntelReqdSubGroupSize(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelReqdSubGroupSizeAttr * MergeIntelReqdSubGroupSizeAttr(Decl *D, const IntelReqdSubGroupSizeAttr &A); IntelNamedSubGroupSizeAttr * MergeIntelNamedSubGroupSizeAttr(Decl *D, const IntelNamedSubGroupSizeAttr &A); void AddSYCLIntelNumSimdWorkItemsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelNumSimdWorkItemsAttr * MergeSYCLIntelNumSimdWorkItemsAttr(Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A); void AddSYCLIntelESimdVectorizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelESimdVectorizeAttr * MergeSYCLIntelESimdVectorizeAttr(Decl *D, const SYCLIntelESimdVectorizeAttr &A); void AddSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelSchedulerTargetFmaxMhzAttr *MergeSYCLIntelSchedulerTargetFmaxMhzAttr( Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A); void AddSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelNoGlobalWorkOffsetAttr *MergeSYCLIntelNoGlobalWorkOffsetAttr( Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A); void AddSYCLIntelLoopFuseAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelLoopFuseAttr * MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A); void AddIntelFPGAPrivateCopiesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); void AddIntelFPGAMaxReplicatesAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGAMaxReplicatesAttr * MergeIntelFPGAMaxReplicatesAttr(Decl *D, const IntelFPGAMaxReplicatesAttr &A); void AddIntelFPGAForcePow2DepthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGAForcePow2DepthAttr * MergeIntelFPGAForcePow2DepthAttr(Decl *D, const IntelFPGAForcePow2DepthAttr &A); void AddSYCLIntelFPGAInitiationIntervalAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelFPGAInitiationIntervalAttr *MergeSYCLIntelFPGAInitiationIntervalAttr( Decl *D, const SYCLIntelFPGAInitiationIntervalAttr &A); SYCLIntelFPGAMaxConcurrencyAttr *MergeSYCLIntelFPGAMaxConcurrencyAttr( Decl *D, const SYCLIntelFPGAMaxConcurrencyAttr &A); void AddSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); SYCLIntelMaxGlobalWorkDimAttr * MergeSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A); void AddIntelFPGABankWidthAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGABankWidthAttr * MergeIntelFPGABankWidthAttr(Decl *D, const IntelFPGABankWidthAttr &A); void AddIntelFPGANumBanksAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); IntelFPGANumBanksAttr * MergeIntelFPGANumBanksAttr(Decl *D, const IntelFPGANumBanksAttr &A); SYCLDeviceHasAttr *MergeSYCLDeviceHasAttr(Decl *D, const SYCLDeviceHasAttr &A); void AddSYCLDeviceHasAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size); SYCLUsesAspectsAttr *MergeSYCLUsesAspectsAttr(Decl *D, const SYCLUsesAspectsAttr &A); void AddSYCLUsesAspectsAttr(Decl *D, const AttributeCommonInfo &CI, Expr **Exprs, unsigned Size); /// AddAlignedAttr - Adds an aligned attribute to a particular declaration. void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, bool IsPackExpansion); void AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, TypeSourceInfo *T, bool IsPackExpansion); /// AddAssumeAlignedAttr - Adds an assume_aligned attribute to a particular /// declaration. void AddAssumeAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, Expr *OE); /// AddAllocAlignAttr - Adds an alloc_align attribute to a particular /// declaration. void AddAllocAlignAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ParamExpr); /// AddAlignValueAttr - Adds an align_value attribute to a particular /// declaration. void AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); /// AddAnnotationAttr - Adds an annotation Annot with Args arguments to D. void AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Annot, MutableArrayRef<Expr *> Args); /// AddLaunchBoundsAttr - Adds a launch_bounds attribute to a particular /// declaration. void AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, Expr *MaxThreads, Expr *MinBlocks); /// AddModeAttr - Adds a mode attribute to a particular declaration. void AddModeAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Name, bool InInstantiation = false); void AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, ParameterABI ABI); enum class RetainOwnershipKind {NS, CF, OS}; void AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, RetainOwnershipKind K, bool IsTemplateInstantiation); /// addAMDGPUFlatWorkGroupSizeAttr - Adds an amdgpu_flat_work_group_size /// attribute to a particular declaration. void addAMDGPUFlatWorkGroupSizeAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addAMDGPUWavePersEUAttr - Adds an amdgpu_waves_per_eu attribute to a /// particular declaration. void addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, Expr *Min, Expr *Max); /// addSYCLIntelPipeIOAttr - Adds a pipe I/O attribute to a particular /// declaration. void addSYCLIntelPipeIOAttr(Decl *D, const AttributeCommonInfo &CI, Expr *ID); /// AddSYCLIntelFPGAMaxConcurrencyAttr - Adds a max_concurrency attribute to a /// particular declaration. void AddSYCLIntelFPGAMaxConcurrencyAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E); bool checkNSReturnsRetainedReturnType(SourceLocation loc, QualType type); bool checkAllowedSYCLInitializer(VarDecl *VD); //===--------------------------------------------------------------------===// // 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); /// Lookup 'coroutine_traits' in std namespace and std::experimental /// namespace. The namespace found is recorded in Namespace. ClassTemplateDecl *lookupCoroutineTraits(SourceLocation KwLoc, SourceLocation FuncLoc, NamespaceDecl *&Namespace); /// Check that the expression co_await promise.final_suspend() shall not be /// potentially-throwing. bool checkFinalSuspendNoThrow(const Stmt *FinalSuspend); //===--------------------------------------------------------------------===// // OpenMP directives and clauses. // private: void *VarDataSharingAttributesStack; struct DeclareTargetContextInfo { struct MapInfo { OMPDeclareTargetDeclAttr::MapTypeTy MT; SourceLocation Loc; }; /// Explicitly listed variables and functions in a 'to' or 'link' clause. llvm::DenseMap<NamedDecl *, MapInfo> ExplicitlyMapped; /// The 'device_type' as parsed from the clause. OMPDeclareTargetDeclAttr::DevTypeTy DT = OMPDeclareTargetDeclAttr::DT_Any; /// The directive kind, `begin declare target` or `declare target`. OpenMPDirectiveKind Kind; /// The directive location. SourceLocation Loc; DeclareTargetContextInfo(OpenMPDirectiveKind Kind, SourceLocation Loc) : Kind(Kind), Loc(Loc) {} }; /// Number of nested '#pragma omp declare target' directives. SmallVector<DeclareTargetContextInfo, 4> DeclareTargetNesting; /// Initialization of data-sharing attributes stack. void InitDataSharingAttributesStack(); void DestroyDataSharingAttributesStack(); ExprResult VerifyPositiveIntegerConstantInClause(Expr *Op, OpenMPClauseKind CKind, bool StrictlyPositive = true, bool SuppressExprDiags = false); /// Returns OpenMP nesting level for current directive. unsigned getOpenMPNestingLevel() const; /// Adjusts the function scopes index for the target-based regions. void adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, unsigned Level) const; /// Returns the number of scopes associated with the construct on the given /// OpenMP level. int getNumberOfConstructScopes(unsigned Level) const; /// Push new OpenMP function region for non-capturing function. void pushOpenMPFunctionRegion(); /// Pop OpenMP function region for non-capturing function. void popOpenMPFunctionRegion(const sema::FunctionScopeInfo *OldFSI); /// Analyzes and checks a loop nest for use by a loop transformation. /// /// \param Kind The loop transformation directive kind. /// \param NumLoops How many nested loops the directive is expecting. /// \param AStmt Associated statement of the transformation directive. /// \param LoopHelpers [out] The loop analysis result. /// \param Body [out] The body code nested in \p NumLoops loop. /// \param OriginalInits [out] Collection of statements and declarations that /// must have been executed/declared before entering the /// loop. /// /// \return Whether there was any error. bool checkTransformableLoopNest( OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, Stmt *&Body, SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> &OriginalInits); /// Helper to keep information about the current `omp begin/end declare /// variant` nesting. struct OMPDeclareVariantScope { /// The associated OpenMP context selector. OMPTraitInfo *TI; /// The associated OpenMP context selector mangling. std::string NameSuffix; OMPDeclareVariantScope(OMPTraitInfo &TI); }; /// Return the OMPTraitInfo for the surrounding scope, if any. OMPTraitInfo *getOMPTraitInfoForSurroundingScope() { return OMPDeclareVariantScopes.empty() ? nullptr : OMPDeclareVariantScopes.back().TI; } /// The current `omp begin/end declare variant` scopes. SmallVector<OMPDeclareVariantScope, 4> OMPDeclareVariantScopes; /// The current `omp begin/end assumes` scopes. SmallVector<AssumptionAttr *, 4> OMPAssumeScoped; /// All `omp assumes` we encountered so far. SmallVector<AssumptionAttr *, 4> OMPAssumeGlobal; public: /// The declarator \p D defines a function in the scope \p S which is nested /// in an `omp begin/end declare variant` scope. In this method we create a /// declaration for \p D and rename \p D according to the OpenMP context /// selector of the surrounding scope. Return all base functions in \p Bases. void ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists, SmallVectorImpl<FunctionDecl *> &Bases); /// Register \p D as specialization of all base functions in \p Bases in the /// current `omp begin/end declare variant` scope. void ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( Decl *D, SmallVectorImpl<FunctionDecl *> &Bases); /// Act on \p D, a function definition inside of an `omp [begin/end] assumes`. void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D); /// Can we exit an OpenMP declare variant scope at the moment. bool isInOpenMPDeclareVariantScope() const { return !OMPDeclareVariantScopes.empty(); } /// Given the potential call expression \p Call, determine if there is a /// specialization via the OpenMP declare variant mechanism available. If /// there is, return the specialized call expression, otherwise return the /// original \p Call. ExprResult ActOnOpenMPCall(ExprResult Call, Scope *Scope, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig); /// Handle a `omp begin declare variant`. void ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, OMPTraitInfo &TI); /// Handle a `omp end declare variant`. void ActOnOpenMPEndDeclareVariant(); /// Checks if the variant/multiversion functions are compatible. bool areMultiversionVariantFunctionsCompatible( const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer); /// Function tries to capture lambda's captured variables in the OpenMP region /// before the original lambda is captured. void tryCaptureOpenMPLambdas(ValueDecl *V); /// Return true if the provided declaration \a VD should be captured by /// reference. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. /// \param OpenMPCaptureLevel Capture level within an OpenMP construct. bool isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, unsigned OpenMPCaptureLevel) const; /// Check if the specified variable is used in one of the private /// clauses (private, firstprivate, lastprivate, reduction etc.) in OpenMP /// constructs. VarDecl *isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo = false, unsigned StopAt = 0); ExprResult getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, ExprObjectKind OK, SourceLocation Loc); /// If the current region is a loop-based region, mark the start of the loop /// construct. void startOpenMPLoop(); /// If the current region is a range loop-based region, mark the start of the /// loop construct. void startOpenMPCXXRangeFor(); /// Check if the specified variable is used in 'private' clause. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. OpenMPClauseKind isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, unsigned CapLevel) const; /// Sets OpenMP capture kind (OMPC_private, OMPC_firstprivate, OMPC_map etc.) /// for \p FD based on DSA for the provided corresponding captured declaration /// \p D. void setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, unsigned Level); /// Check if the specified variable is captured by 'target' directive. /// \param Level Relative level of nested OpenMP construct for that the check /// is performed. bool isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; /// Check if the specified global variable must be captured by outer capture /// regions. /// \param Level Relative level of nested OpenMP construct for that /// the check is performed. bool isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, unsigned CaptureLevel) const; ExprResult PerformOpenMPImplicitIntegerConversion(SourceLocation OpLoc, Expr *Op); /// Called on start of new data sharing attribute block. void StartOpenMPDSABlock(OpenMPDirectiveKind K, const DeclarationNameInfo &DirName, Scope *CurScope, SourceLocation Loc); /// Start analysis of clauses. void StartOpenMPClause(OpenMPClauseKind K); /// End analysis of clauses. void EndOpenMPClause(); /// Called on end of data sharing attribute block. void EndOpenMPDSABlock(Stmt *CurDirective); /// Check if the current region is an OpenMP loop region and if it is, /// mark loop control variable, used in \p Init for loop initialization, as /// private by default. /// \param Init First part of the for loop. void ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init); /// Called on well-formed '\#pragma omp metadirective' after parsing /// of the associated statement. StmtResult ActOnOpenMPMetaDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); // OpenMP directives and clauses. /// Called on correct id-expression from the '#pragma omp /// threadprivate'. ExprResult ActOnOpenMPIdExpression(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id, OpenMPDirectiveKind Kind); /// Called on well-formed '#pragma omp threadprivate'. DeclGroupPtrTy ActOnOpenMPThreadprivateDirective( SourceLocation Loc, ArrayRef<Expr *> VarList); /// Builds a new OpenMPThreadPrivateDecl and checks its correctness. OMPThreadPrivateDecl *CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList); /// Called on well-formed '#pragma omp allocate'. DeclGroupPtrTy ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, ArrayRef<OMPClause *> Clauses, DeclContext *Owner = nullptr); /// Called on well-formed '#pragma omp [begin] assume[s]'. void ActOnOpenMPAssumesDirective(SourceLocation Loc, OpenMPDirectiveKind DKind, ArrayRef<std::string> Assumptions, bool SkippedClauses); /// Check if there is an active global `omp begin assumes` directive. bool isInOpenMPAssumeScope() const { return !OMPAssumeScoped.empty(); } /// Check if there is an active global `omp assumes` directive. bool hasGlobalOpenMPAssumes() const { return !OMPAssumeGlobal.empty(); } /// Called on well-formed '#pragma omp end assumes'. void ActOnOpenMPEndAssumesDirective(); /// Called on well-formed '#pragma omp requires'. DeclGroupPtrTy ActOnOpenMPRequiresDirective(SourceLocation Loc, ArrayRef<OMPClause *> ClauseList); /// Check restrictions on Requires directive OMPRequiresDecl *CheckOMPRequiresDecl(SourceLocation Loc, ArrayRef<OMPClause *> Clauses); /// Check if the specified type is allowed to be used in 'omp declare /// reduction' construct. QualType ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveStart( Scope *S, DeclContext *DC, DeclarationName Name, ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, AccessSpecifier AS, Decl *PrevDeclInScope = nullptr); /// Initialize declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner); /// Initialize declare reduction construct initializer. /// \return omp_priv variable. VarDecl *ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D); /// Finish current declare reduction construct initializer. void ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, VarDecl *OmpPrivParm); /// Called at the end of '#pragma omp declare reduction'. DeclGroupPtrTy ActOnOpenMPDeclareReductionDirectiveEnd( Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid); /// Check variable declaration in 'omp declare mapper' construct. TypeResult ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D); /// Check if the specified type is allowed to be used in 'omp declare /// mapper' construct. QualType ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, TypeResult ParsedType); /// Called on start of '#pragma omp declare mapper'. DeclGroupPtrTy ActOnOpenMPDeclareMapperDirective( Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope = nullptr); /// Build the mapper variable of '#pragma omp declare mapper'. ExprResult ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, SourceLocation StartLoc, DeclarationName VN); bool isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const; const ValueDecl *getOpenMPDeclareMapperVarName() const; /// Called on the start of target region i.e. '#pragma omp declare target'. bool ActOnStartOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Called at the end of target region i.e. '#pragma omp end declare target'. const DeclareTargetContextInfo ActOnOpenMPEndDeclareTargetDirective(); /// Called once a target context is completed, that can be when a /// '#pragma omp end declare target' was encountered or when a /// '#pragma omp declare target' without declaration-definition-seq was /// encountered. void ActOnFinishedOpenMPDeclareTargetContext(DeclareTargetContextInfo &DTCI); /// Searches for the provided declaration name for OpenMP declare target /// directive. NamedDecl *lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec, const DeclarationNameInfo &Id); /// Called on correct id-expression from the '#pragma omp declare target'. void ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, OMPDeclareTargetDeclAttr::DevTypeTy DT); /// Check declaration inside target region. void checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, SourceLocation IdLoc = SourceLocation()); /// Finishes analysis of the deferred functions calls that may be declared as /// host/nohost during device/host compilation. void finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc); /// Return true inside OpenMP declare target region. bool isInOpenMPDeclareTargetContext() const { return !DeclareTargetNesting.empty(); } /// Return true inside OpenMP target region. bool isInOpenMPTargetExecutionDirective() const; /// Return the number of captured regions created for an OpenMP directive. static int getOpenMPCaptureLevels(OpenMPDirectiveKind Kind); /// Initialization of captured region for OpenMP region. void ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope); /// Called for syntactical loops (ForStmt or CXXForRangeStmt) associated to /// an OpenMP loop directive. StmtResult ActOnOpenMPCanonicalLoop(Stmt *AStmt); /// Process a canonical OpenMP loop nest that can either be a canonical /// literal loop (ForStmt or CXXForRangeStmt), or the generated loop of an /// OpenMP loop transformation construct. StmtResult ActOnOpenMPLoopnest(Stmt *AStmt); /// 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 tile' after parsing of its clauses and /// the associated statement. StmtResult ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '#pragma omp unroll' after parsing of its clauses /// and the associated statement. StmtResult ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp for' after parsing /// of the associated statement. StmtResult ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp for simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPForSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp sections' after parsing /// of the associated statement. StmtResult ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp section' after parsing of the /// associated statement. StmtResult ActOnOpenMPSectionDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp single' after parsing of the /// associated statement. StmtResult ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp master' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterDirective(Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp critical' after parsing of the /// associated statement. StmtResult ActOnOpenMPCriticalDirective(const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel for' after parsing /// of the associated statement. StmtResult ActOnOpenMPParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp parallel sections' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp task' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskyield'. StmtResult ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp barrier'. StmtResult ActOnOpenMPBarrierDirective(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskwait'. StmtResult ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp taskgroup'. StmtResult ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp flush'. StmtResult ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp depobj'. StmtResult ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp scan'. StmtResult ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp ordered' after parsing of the /// associated statement. StmtResult ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp atomic' after parsing of the /// associated statement. StmtResult ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target data' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target enter data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target exit data' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp target parallel' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp cancellation point'. StmtResult ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp cancel'. StmtResult ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, OpenMPDirectiveKind CancelRegion); /// Called on well-formed '\#pragma omp taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPTaskLoopDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop' after parsing of the /// associated statement. StmtResult ActOnOpenMPMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp master taskloop simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp parallel master taskloop simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPParallelMasterTaskLoopSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPDistributeDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target update'. StmtResult ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc, Stmt *AStmt); /// Called on well-formed '\#pragma omp distribute parallel for' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target parallel for simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target simd' after parsing of /// the associated statement. StmtResult ActOnOpenMPTargetSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute' after parsing of /// the associated statement. StmtResult ActOnOpenMPTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute simd' after parsing /// of the associated statement. StmtResult ActOnOpenMPTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for simd' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams' after parsing of the /// associated statement. StmtResult ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp target teams distribute' after parsing /// of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for' /// after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute parallel for /// simd' after parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp target teams distribute simd' after /// parsing of the associated statement. StmtResult ActOnOpenMPTargetTeamsDistributeSimdDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Called on well-formed '\#pragma omp interop'. StmtResult ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp dispatch' after parsing of the // /associated statement. StmtResult ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp masked' after parsing of the // /associated statement. StmtResult ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed '\#pragma omp loop' after parsing of the /// associated statement. StmtResult ActOnOpenMPGenericLoopDirective( ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA); /// Checks correctness of linear modifiers. bool CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, SourceLocation LinLoc); /// Checks that the specified declaration matches requirements for the linear /// decls. bool CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, OpenMPLinearClauseKind LinKind, QualType Type, bool IsDeclareSimd = false); /// Called on well-formed '\#pragma omp declare simd' after parsing of /// the associated method/function. DeclGroupPtrTy ActOnOpenMPDeclareSimdDirective( DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR); /// Checks '\#pragma omp declare variant' variant function and original /// functions after parsing of the associated method/function. /// \param DG Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The trait info object representing the match clause. /// \param NumAppendArgs The number of omp_interop_t arguments to account for /// in checking. /// \returns None, if the function/variant function are not compatible with /// the pragma, pair of original function/variant ref expression otherwise. Optional<std::pair<FunctionDecl *, Expr *>> checkOpenMPDeclareVariantFunction(DeclGroupPtrTy DG, Expr *VariantRef, OMPTraitInfo &TI, unsigned NumAppendArgs, SourceRange SR); /// Called on well-formed '\#pragma omp declare variant' after parsing of /// the associated method/function. /// \param FD Function declaration to which declare variant directive is /// applied to. /// \param VariantRef Expression that references the variant function, which /// must be used instead of the original one, specified in \p DG. /// \param TI The context traits associated with the function variant. /// \param AdjustArgsNothing The list of 'nothing' arguments. /// \param AdjustArgsNeedDevicePtr The list of 'need_device_ptr' arguments. /// \param AppendArgs The list of 'append_args' arguments. /// \param AdjustArgsLoc The Location of an 'adjust_args' clause. /// \param AppendArgsLoc The Location of an 'append_args' clause. /// \param SR The SourceRange of the 'declare variant' directive. void ActOnOpenMPDeclareVariantDirective( FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, ArrayRef<Expr *> AdjustArgsNothing, ArrayRef<Expr *> AdjustArgsNeedDevicePtr, ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, SourceRange SR); OMPClause *ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocator' clause. OMPClause *ActOnOpenMPAllocatorClause(Expr *Allocator, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'if' clause. OMPClause *ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'final' clause. OMPClause *ActOnOpenMPFinalClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_threads' clause. OMPClause *ActOnOpenMPNumThreadsClause(Expr *NumThreads, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'align' clause. OMPClause *ActOnOpenMPAlignClause(Expr *Alignment, 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-form 'sizes' clause. OMPClause *ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-form 'full' clauses. OMPClause *ActOnOpenMPFullClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-form 'partial' clauses. OMPClause *ActOnOpenMPPartialClause(Expr *FactorExpr, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'collapse' clause. OMPClause *ActOnOpenMPCollapseClause(Expr *NumForLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'ordered' clause. OMPClause * ActOnOpenMPOrderedClause(SourceLocation StartLoc, SourceLocation EndLoc, SourceLocation LParenLoc = SourceLocation(), Expr *NumForLoops = nullptr); /// Called on well-formed 'grainsize' clause. OMPClause *ActOnOpenMPGrainsizeClause(Expr *Size, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'num_tasks' clause. OMPClause *ActOnOpenMPNumTasksClause(Expr *NumTasks, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'hint' clause. OMPClause *ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'detach' clause. OMPClause *ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSimpleClause(OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'when' clause. OMPClause *ActOnOpenMPWhenClause(OMPTraitInfo &TI, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'default' clause. OMPClause *ActOnOpenMPDefaultClause(llvm::omp::DefaultKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'proc_bind' clause. OMPClause *ActOnOpenMPProcBindClause(llvm::omp::ProcBindKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'order' clause. OMPClause *ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPSingleExprWithArgClause( OpenMPClauseKind Kind, ArrayRef<unsigned> Arguments, Expr *Expr, SourceLocation StartLoc, SourceLocation LParenLoc, ArrayRef<SourceLocation> ArgumentsLoc, SourceLocation DelimLoc, SourceLocation EndLoc); /// Called on well-formed 'schedule' clause. OMPClause *ActOnOpenMPScheduleClause( OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nowait' clause. OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'untied' clause. OMPClause *ActOnOpenMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'mergeable' clause. OMPClause *ActOnOpenMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'read' clause. OMPClause *ActOnOpenMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'write' clause. OMPClause *ActOnOpenMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'update' clause. OMPClause *ActOnOpenMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'capture' clause. OMPClause *ActOnOpenMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'seq_cst' clause. OMPClause *ActOnOpenMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acq_rel' clause. OMPClause *ActOnOpenMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'acquire' clause. OMPClause *ActOnOpenMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'release' clause. OMPClause *ActOnOpenMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'relaxed' clause. OMPClause *ActOnOpenMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'init' clause. OMPClause *ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'use' clause. OMPClause *ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'destroy' clause. OMPClause *ActOnOpenMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Called on well-formed 'novariants' clause. OMPClause *ActOnOpenMPNovariantsClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'nocontext' clause. OMPClause *ActOnOpenMPNocontextClause(Expr *Condition, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'filter' clause. OMPClause *ActOnOpenMPFilterClause(Expr *ThreadID, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'threads' clause. OMPClause *ActOnOpenMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'simd' clause. OMPClause *ActOnOpenMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'nogroup' clause. OMPClause *ActOnOpenMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'unified_address' clause. OMPClause *ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'reverse_offload' clause. OMPClause *ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'dynamic_allocators' clause. OMPClause *ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc); /// Called on well-formed 'atomic_default_mem_order' clause. OMPClause *ActOnOpenMPAtomicDefaultMemOrderClause( OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); OMPClause *ActOnOpenMPVarListClause( OpenMPClauseKind Kind, ArrayRef<Expr *> Vars, Expr *DepModOrTailExpr, const OMPVarListLocTy &Locs, SourceLocation ColonLoc, CXXScopeSpec &ReductionOrMapperIdScopeSpec, DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, SourceLocation ExtraModifierLoc, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc); /// Called on well-formed 'inclusive' clause. OMPClause *ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'exclusive' clause. OMPClause *ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'allocate' clause. OMPClause * ActOnOpenMPAllocateClause(Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'private' clause. OMPClause *ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'firstprivate' clause. OMPClause *ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'lastprivate' clause. OMPClause *ActOnOpenMPLastprivateClause( ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'shared' clause. OMPClause *ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'reduction' clause. OMPClause *ActOnOpenMPReductionClause( ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'task_reduction' clause. OMPClause *ActOnOpenMPTaskReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'in_reduction' clause. OMPClause *ActOnOpenMPInReductionClause( ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, ArrayRef<Expr *> UnresolvedReductions = llvm::None); /// Called on well-formed 'linear' clause. OMPClause * ActOnOpenMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'aligned' clause. OMPClause *ActOnOpenMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc); /// Called on well-formed 'copyin' clause. OMPClause *ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'copyprivate' clause. OMPClause *ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'flush' pseudo clause. OMPClause *ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depobj' pseudo clause. OMPClause *ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'depend' clause. OMPClause * ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'device' clause. OMPClause *ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *Device, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc); /// Called on well-formed 'map' clause. OMPClause *ActOnOpenMPMapClause( ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, ArrayRef<SourceLocation> MapTypeModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, bool NoDiagnose = false, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'num_teams' clause. OMPClause *ActOnOpenMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'thread_limit' clause. OMPClause *ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'priority' clause. OMPClause *ActOnOpenMPPriorityClause(Expr *Priority, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Called on well-formed 'dist_schedule' clause. OMPClause *ActOnOpenMPDistScheduleClause( OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc); /// Called on well-formed 'defaultmap' clause. OMPClause *ActOnOpenMPDefaultmapClause( OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KindLoc, SourceLocation EndLoc); /// Called on well-formed 'to' clause. OMPClause * ActOnOpenMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'from' clause. OMPClause * ActOnOpenMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, SourceLocation ColonLoc, ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers = llvm::None); /// Called on well-formed 'use_device_ptr' clause. OMPClause *ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'use_device_addr' clause. OMPClause *ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'is_device_ptr' clause. OMPClause *ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs); /// Called on well-formed 'nontemporal' clause. OMPClause *ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Data for list of allocators. struct UsesAllocatorsData { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; /// Called on well-formed 'uses_allocators' clause. OMPClause *ActOnOpenMPUsesAllocatorClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<UsesAllocatorsData> Data); /// Called on well-formed 'affinity' clause. OMPClause *ActOnOpenMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// Called on a well-formed 'bind' clause. OMPClause *ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, SourceLocation KindLoc, 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_PRValue, 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 function is a no-op if the operand has a function type // or an array type. ExprResult DefaultLvalueConversion(Expr *E); // DefaultArgumentPromotion (C99 6.5.2.2p6). Used for function calls that // do not have a prototype. Integer promotions are performed on each // argument, and arguments that have type float are promoted to double. ExprResult DefaultArgumentPromotion(Expr *E); /// If \p E is a prvalue denoting an unmaterialized temporary, materialize /// it as an xvalue. In C++98, the result will still be a prvalue, because /// we don't have xvalues there. ExprResult TemporaryMaterializationConversion(Expr *E); // Used for emitting the right warning by DefaultVariadicArgumentPromotion enum VariadicCallType { VariadicFunction, VariadicBlock, VariadicMethod, VariadicConstructor, VariadicDoesNotApply }; VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn); // Used for determining in which context a type is allowed to be passed to a // vararg function. enum VarArgKind { VAK_Valid, VAK_ValidInCXX11, VAK_Undefined, VAK_MSVCUndefined, VAK_Invalid }; // Determines which VarArgKind fits an expression. VarArgKind isValidVarArgType(const QualType &Ty); /// Check to see if the given expression is a valid argument to a variadic /// function, issuing a diagnostic if not. void checkVariadicArgument(const Expr *E, VariadicCallType CT); /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. In the success case, /// the statement is rewritten to remove implicit nodes from the return /// value. bool checkAndRewriteMustTailAttr(Stmt *St, const Attr &MTA); private: /// Check whether the given statement can have musttail applied to it, /// issuing a diagnostic and returning false if not. bool checkMustTailAttr(const Stmt *St, const Attr &MTA); public: /// Check to see if a given expression could have '.c_str()' called on it. bool hasCStrMethod(const Expr *E); /// GatherArgumentsForCall - Collector argument expressions for various /// form of call prototypes. bool GatherArgumentsForCall(SourceLocation CallLoc, FunctionDecl *FDecl, const FunctionProtoType *Proto, unsigned FirstParam, ArrayRef<Expr *> Args, SmallVectorImpl<Expr *> &AllArgs, VariadicCallType CallType = VariadicDoesNotApply, bool AllowExplicit = false, bool IsListInitialization = false); // DefaultVariadicArgumentPromotion - Like DefaultArgumentPromotion, but // will create a runtime trap if the resulting type is not a POD type. ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl); /// Context in which we're performing a usual arithmetic conversion. enum ArithConvKind { /// An arithmetic operation. ACK_Arithmetic, /// A bitwise operation. ACK_BitwiseOp, /// A comparison. ACK_Comparison, /// A conditional (?:) operator. ACK_Conditional, /// A compound assignment expression. ACK_CompAssign, }; // UsualArithmeticConversions - performs the UsualUnaryConversions on it's // operands and then handles various conversions that are common to binary // operators (C99 6.3.1.8). If both operands aren't arithmetic, this // routine returns the first non-arithmetic type found. The client is // responsible for emitting appropriate error diagnostics. QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK); /// AssignConvertType - All of the 'assignment' semantic checks return this /// enum to indicate whether the assignment was allowed. These checks are /// done for simple assignments, as well as initialization, return from /// function, argument passing, etc. The query is phrased in terms of a /// source and destination type. enum AssignConvertType { /// Compatible - the types are compatible according to the standard. Compatible, /// PointerToInt - The assignment converts a pointer to an int, which we /// accept as an extension. PointerToInt, /// IntToPointer - The assignment converts an int to a pointer, which we /// accept as an extension. IntToPointer, /// FunctionVoidPointer - The assignment is between a function pointer and /// void*, which the standard doesn't allow, but we accept as an extension. FunctionVoidPointer, /// IncompatiblePointer - The assignment is between two pointers types that /// are not compatible, but we accept them as an extension. IncompatiblePointer, /// IncompatibleFunctionPointer - The assignment is between two function /// pointers types that are not compatible, but we accept them as an /// extension. IncompatibleFunctionPointer, /// IncompatiblePointerSign - The assignment is between two pointers types /// which point to integers which have a different sign, but are otherwise /// identical. This is a subset of the above, but broken out because it's by /// far the most common case of incompatible pointers. IncompatiblePointerSign, /// CompatiblePointerDiscardsQualifiers - The assignment discards /// c/v/r qualifiers, which we accept as an extension. CompatiblePointerDiscardsQualifiers, /// IncompatiblePointerDiscardsQualifiers - The assignment /// discards qualifiers that we don't permit to be discarded, /// like address spaces. IncompatiblePointerDiscardsQualifiers, /// IncompatibleNestedPointerAddressSpaceMismatch - The assignment /// changes address spaces in nested pointer types which is not allowed. /// For instance, converting __private int ** to __generic int ** is /// illegal even though __private could be converted to __generic. IncompatibleNestedPointerAddressSpaceMismatch, /// IncompatibleNestedPointerQualifiers - The assignment is between two /// nested pointer types, and the qualifiers other than the first two /// levels differ e.g. char ** -> const char **, but we accept them as an /// extension. IncompatibleNestedPointerQualifiers, /// IncompatibleVectors - The assignment is between two vector types that /// have the same size, which we accept as an extension. IncompatibleVectors, /// IntToBlockPointer - The assignment converts an int to a block /// pointer. We disallow this. IntToBlockPointer, /// IncompatibleBlockPointer - The assignment is between two block /// pointers types that are not compatible. IncompatibleBlockPointer, /// IncompatibleObjCQualifiedId - The assignment is between a qualified /// id type and something else (that is incompatible with it). For example, /// "id <XXX>" = "Foo *", where "Foo *" doesn't implement the XXX protocol. IncompatibleObjCQualifiedId, /// IncompatibleObjCWeakRef - Assigning a weak-unavailable object to an /// object with __weak qualifier. IncompatibleObjCWeakRef, /// 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, 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_PRValue, CheckedConversionKind CCK = CCK_ImplicitConversion); /// the following "Check" methods will return a valid/converted QualType /// or a null QualType (indicating an error diagnostic was issued). /// type checking binary operators (subroutines of CreateBuiltinBinOp). QualType InvalidOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType InvalidLogicalVectorOperands(SourceLocation Loc, ExprResult &LHS, ExprResult &RHS); QualType CheckPointerToMemberOperands( // C++ 5.5 ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, SourceLocation OpLoc, bool isIndirect); QualType CheckMultiplyDivideOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool IsDivide); QualType CheckRemainderOperands( // C99 6.5.5 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign = false); QualType CheckAdditionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, QualType* CompLHSTy = nullptr); QualType CheckSubtractionOperands( // C99 6.5.6 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, QualType* CompLHSTy = nullptr); QualType CheckShiftOperands( // C99 6.5.7 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc, bool IsCompAssign = false); void CheckPtrComparisonWithNullChar(ExprResult &E, ExprResult &NullE); QualType CheckCompareOperands( // C99 6.5.8/9 ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckBitwiseOperands( // C99 6.5.[10...12] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckLogicalOperands( // C99 6.5.[13,14] ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); // CheckAssignmentOperands is used for both simple and compound assignment. // For simple assignment, pass both expressions and a null converted type. // For compound assignment, pass both expressions and the converted type. QualType CheckAssignmentOperands( // C99 6.5.16.[1,2] Expr *LHSExpr, ExprResult &RHS, SourceLocation Loc, QualType CompoundType); ExprResult checkPseudoObjectIncDec(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opcode, Expr *Op); ExprResult checkPseudoObjectAssignment(Scope *S, SourceLocation OpLoc, BinaryOperatorKind Opcode, Expr *LHS, Expr *RHS); ExprResult checkPseudoObjectRValue(Expr *E); Expr *recreateSyntacticForm(PseudoObjectExpr *E); QualType CheckConditionalOperands( // C99 6.5.15 ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation QuestionLoc); QualType CXXCheckConditionalOperands( // C++ 5.16 ExprResult &cond, ExprResult &lhs, ExprResult &rhs, ExprValueKind &VK, ExprObjectKind &OK, SourceLocation questionLoc); QualType CheckVectorConditionalTypes(ExprResult &Cond, ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); QualType FindCompositePointerType(SourceLocation Loc, Expr *&E1, Expr *&E2, bool ConvertArgs = true); QualType FindCompositePointerType(SourceLocation Loc, ExprResult &E1, ExprResult &E2, bool ConvertArgs = true) { Expr *E1Tmp = E1.get(), *E2Tmp = E2.get(); QualType Composite = FindCompositePointerType(Loc, E1Tmp, E2Tmp, ConvertArgs); E1 = E1Tmp; E2 = E2Tmp; return Composite; } QualType FindCompositeObjCPointerType(ExprResult &LHS, ExprResult &RHS, SourceLocation QuestionLoc); bool DiagnoseConditionalForNull(Expr *LHSExpr, Expr *RHSExpr, SourceLocation QuestionLoc); void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range); /// type checking for vector binary operators. QualType CheckVectorOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign, bool AllowBothBool, bool AllowBoolConversion); QualType GetSignedVectorType(QualType V); QualType CheckVectorCompareOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, BinaryOperatorKind Opc); QualType CheckVectorLogicalOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc); /// Type checking for matrix binary operators. QualType CheckMatrixElementwiseOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); QualType CheckMatrixMultiplyOperands(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, bool IsCompAssign); bool isValidSveBitcast(QualType srcType, QualType destType); bool areMatrixTypesOfTheSameDimension(QualType srcTy, QualType destTy); bool areVectorTypesSameSize(QualType srcType, QualType destType); bool areLaxCompatibleVectorTypes(QualType srcType, QualType destType); bool isLaxVectorConversion(QualType srcType, QualType destType); /// type checking declaration initializers (C99 6.7.8) bool CheckForConstantInitializer(Expr *e, QualType t); // type checking C++ declaration initializers (C++ [dcl.init]). /// ReferenceCompareResult - Expresses the result of comparing two /// types (cv1 T1 and cv2 T2) to determine their compatibility for the /// purposes of initialization by reference (C++ [dcl.init.ref]p4). enum ReferenceCompareResult { /// Ref_Incompatible - The two types are incompatible, so direct /// reference binding is not possible. Ref_Incompatible = 0, /// Ref_Related - The two types are reference-related, which means /// that their unqualified forms (T1 and T2) are either the same /// or T1 is a base class of T2. Ref_Related, /// Ref_Compatible - The two types are reference-compatible. Ref_Compatible }; // Fake up a scoped enumeration that still contextually converts to bool. struct ReferenceConversionsScope { /// The conversions that would be performed on an lvalue of type T2 when /// binding a reference of type T1 to it, as determined when evaluating /// whether T1 is reference-compatible with T2. enum ReferenceConversions { Qualification = 0x1, NestedQualification = 0x2, Function = 0x4, DerivedToBase = 0x8, ObjC = 0x10, ObjCLifetime = 0x20, LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/ObjCLifetime) }; }; using ReferenceConversions = ReferenceConversionsScope::ReferenceConversions; ReferenceCompareResult CompareReferenceRelationship(SourceLocation Loc, QualType T1, QualType T2, ReferenceConversions *Conv = nullptr); ExprResult checkUnknownAnyCast(SourceRange TypeRange, QualType CastType, Expr *CastExpr, CastKind &CastKind, ExprValueKind &VK, CXXCastPath &Path); /// Force an expression with unknown-type to an expression of the /// given type. ExprResult forceUnknownAnyToType(Expr *E, QualType ToType); /// Type-check an expression that's being passed to an /// __unknown_anytype parameter. ExprResult checkUnknownAnyArg(SourceLocation callLoc, Expr *result, QualType &paramType); // CheckMatrixCast - Check type constraints for matrix casts. // We allow casting between matrixes of the same dimensions i.e. when they // have the same number of rows and column. Returns true if the cast is // invalid. bool CheckMatrixCast(SourceRange R, QualType DestTy, QualType SrcTy, CastKind &Kind); // CheckVectorCast - check type constraints for vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size. // returns true if the cast is invalid bool CheckVectorCast(SourceRange R, QualType VectorTy, QualType Ty, CastKind &Kind); /// Prepare `SplattedExpr` for a vector splat operation, adding /// implicit casts if necessary. ExprResult prepareVectorSplat(QualType VectorTy, Expr *SplattedExpr); // CheckExtVectorCast - check type constraints for extended vectors. // Since vectors are an extension, there are no C standard reference for this. // We allow casting between vectors and integer datatypes of the same size, // or vectors and the element type of that vector. // returns the cast expr ExprResult CheckExtVectorCast(SourceRange R, QualType DestTy, Expr *CastExpr, CastKind &Kind); ExprResult BuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo, QualType Type, SourceLocation LParenLoc, Expr *CastExpr, SourceLocation RParenLoc); enum ARCConversionResult { ACR_okay, ACR_unbridged, ACR_error }; /// Checks for invalid conversions and casts between /// retainable pointers and other pointer kinds for ARC and Weak. ARCConversionResult CheckObjCConversion(SourceRange castRange, QualType castType, Expr *&op, CheckedConversionKind CCK, bool Diagnose = true, bool DiagnoseCFAudited = false, BinaryOperatorKind Opc = BO_PtrMemD ); Expr *stripARCUnbridgedCast(Expr *e); void diagnoseARCUnbridgedCast(Expr *e); bool CheckObjCARCUnavailableWeakConversion(QualType castType, QualType ExprType); /// checkRetainCycles - Check whether an Objective-C message send /// might create an obvious retain cycle. void checkRetainCycles(ObjCMessageExpr *msg); void checkRetainCycles(Expr *receiver, Expr *argument); void checkRetainCycles(VarDecl *Var, Expr *Init); /// checkUnsafeAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained type. bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS); /// checkUnsafeExprAssigns - Check whether +1 expr is being assigned /// to weak/__unsafe_unretained expression. void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS); /// CheckMessageArgumentTypes - Check types in an Obj-C message send. /// \param Method - May be null. /// \param [out] ReturnType - The return type of the send. /// \return true iff there were any incompatible types. bool CheckMessageArgumentTypes(const Expr *Receiver, QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, SourceRange RecRange, QualType &ReturnType, ExprValueKind &VK); /// Determine the result of a message send expression based on /// the type of the receiver, the method expected to receive the message, /// and the form of the message send. QualType getMessageSendResultType(const Expr *Receiver, QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage); /// If the given expression involves a message send to a method /// with a related result type, emit a note describing what happened. void EmitRelatedResultTypeNote(const Expr *E); /// Given that we had incompatible pointer types in a return /// statement, check whether we're in a method with a related result /// type, and if so, emit a note describing what happened. void EmitRelatedResultTypeNoteForReturn(QualType destType); class ConditionResult { Decl *ConditionVar; FullExprArg Condition; bool Invalid; bool HasKnownValue; bool KnownValue; friend class Sema; ConditionResult(Sema &S, Decl *ConditionVar, FullExprArg Condition, bool IsConstexpr) : ConditionVar(ConditionVar), Condition(Condition), Invalid(false), HasKnownValue(IsConstexpr && Condition.get() && !Condition.get()->isValueDependent()), KnownValue(HasKnownValue && !!Condition.get()->EvaluateKnownConstInt(S.Context)) {} explicit ConditionResult(bool Invalid) : ConditionVar(nullptr), Condition(nullptr), Invalid(Invalid), HasKnownValue(false), KnownValue(false) {} public: ConditionResult() : ConditionResult(false) {} bool isInvalid() const { return Invalid; } std::pair<VarDecl *, Expr *> get() const { return std::make_pair(cast_or_null<VarDecl>(ConditionVar), Condition.get()); } llvm::Optional<bool> getKnownValue() const { if (!HasKnownValue) return None; return KnownValue; } }; static ConditionResult ConditionError() { return ConditionResult(true); } enum class ConditionKind { Boolean, ///< A boolean condition, from 'if', 'while', 'for', or 'do'. ConstexprIf, ///< A constant boolean condition from 'if constexpr'. Switch ///< An integral condition for a 'switch' statement. }; ConditionResult ActOnCondition(Scope *S, SourceLocation Loc, Expr *SubExpr, ConditionKind CK); ConditionResult ActOnConditionVariable(Decl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); DeclResult ActOnCXXConditionDeclaration(Scope *S, Declarator &D); ExprResult CheckConditionVariable(VarDecl *ConditionVar, SourceLocation StmtLoc, ConditionKind CK); ExprResult CheckSwitchCondition(SourceLocation SwitchLoc, Expr *Cond); /// CheckBooleanCondition - Diagnose problems involving the use of /// the given expression as a boolean condition (e.g. in an if /// statement). Also performs the standard function and array /// decays, possibly changing the input variable. /// /// \param Loc - A location associated with the condition, e.g. the /// 'if' keyword. /// \return true iff there were any errors ExprResult CheckBooleanCondition(SourceLocation Loc, Expr *E, bool IsConstexpr = false); /// ActOnExplicitBoolSpecifier - Build an ExplicitSpecifier from an expression /// found in an explicit(bool) specifier. ExplicitSpecifier ActOnExplicitBoolSpecifier(Expr *E); /// tryResolveExplicitSpecifier - Attempt to resolve the explict specifier. /// Returns true if the explicit specifier is now resolved. bool tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec); /// DiagnoseAssignmentAsCondition - Given that an expression is /// being used as a boolean condition, warn if it's an assignment. void DiagnoseAssignmentAsCondition(Expr *E); /// Redundant parentheses over an equality comparison can indicate /// that the user intended an assignment used as condition. void DiagnoseEqualityWithExtraParens(ParenExpr *ParenE); /// CheckCXXBooleanCondition - Returns true if conversion to bool is invalid. ExprResult CheckCXXBooleanCondition(Expr *CondExpr, bool IsConstexpr = false); /// ConvertIntegerToTypeWarnOnOverflow - Convert the specified APInt to have /// the specified width and sign. If an overflow occurs, detect it and emit /// the specified diagnostic. void ConvertIntegerToTypeWarnOnOverflow(llvm::APSInt &OldVal, unsigned NewWidth, bool NewSign, SourceLocation Loc, unsigned DiagID); /// Checks that the Objective-C declaration is declared in the global scope. /// Emits an error and marks the declaration as invalid if it's not declared /// in the global scope. bool CheckObjCDeclScope(Decl *D); /// Abstract base class used for diagnosing integer constant /// expression violations. class VerifyICEDiagnoser { public: bool Suppress; VerifyICEDiagnoser(bool Suppress = false) : Suppress(Suppress) { } virtual SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc, QualType T); virtual SemaDiagnosticBuilder diagnoseNotICE(Sema &S, SourceLocation Loc) = 0; virtual SemaDiagnosticBuilder diagnoseFold(Sema &S, SourceLocation Loc); virtual ~VerifyICEDiagnoser() {} }; enum AllowFoldKind { NoFold, AllowFold, }; /// VerifyIntegerConstantExpression - Verifies that an expression is an ICE, /// and reports the appropriate diagnostics. Returns false on success. /// Can optionally return the value of the expression. ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, VerifyICEDiagnoser &Diagnoser, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result, unsigned DiagID, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, llvm::APSInt *Result = nullptr, AllowFoldKind CanFold = NoFold); ExprResult VerifyIntegerConstantExpression(Expr *E, AllowFoldKind CanFold = NoFold) { return VerifyIntegerConstantExpression(E, nullptr, CanFold); } /// VerifyBitField - verifies that a bit field expression is an ICE and has /// the correct width, and that the field type is valid. /// Returns false on success. /// Can optionally return whether the bit-field is of width 0 ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth = nullptr); private: unsigned ForceCUDAHostDeviceDepth = 0; public: /// Increments our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. So long as this count is greater /// than zero, all functions encountered will be __host__ __device__. void PushForceCUDAHostDevice(); /// Decrements our count of the number of times we've seen a pragma forcing /// functions to be __host__ __device__. Returns false if the count is 0 /// before incrementing, so you can emit an error. bool PopForceCUDAHostDevice(); class DeviceDeferredDiagnostic { public: DeviceDeferredDiagnostic(SourceLocation SL, const PartialDiagnostic &PD, DeviceDiagnosticReason R) : Diagnostic(SL, PD), Reason(R) {} PartialDiagnosticAt &getDiag() { return Diagnostic; } DeviceDiagnosticReason getReason() const { return Reason; } private: PartialDiagnosticAt Diagnostic; DeviceDiagnosticReason Reason; }; /// 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<DeviceDeferredDiagnostic>> DeviceDeferredDiags; /// A pair of a canonical FunctionDecl and a SourceLocation. When used as the /// key in a hashtable, both the FD and location are hashed. struct FunctionDeclAndLoc { CanonicalDeclPtr<FunctionDecl> FD; SourceLocation Loc; }; /// FunctionDecls and SourceLocations for which CheckCUDACall has emitted a /// (maybe deferred) "bad call" diagnostic. We use this to avoid emitting the /// same deferred diag twice. llvm::DenseSet<FunctionDeclAndLoc> LocsWithCUDACallDiags; /// An inverse call graph, mapping known-emitted functions to one of their /// known-emitted callers (plus the location of the call). /// /// Functions that we can tell a priori must be emitted aren't added to this /// map. llvm::DenseMap</* Callee = */ CanonicalDeclPtr<FunctionDecl>, /* Caller = */ FunctionDeclAndLoc> DeviceKnownEmittedFns; /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a __host__ function, does not emit any diagnostics /// unless \p EmitOnBothSides is true. /// - If CurContext is a __device__ or __global__ function, emits the /// diagnostics immediately. /// - If CurContext is a __host__ __device__ function and we are compiling for /// the device, creates a diagnostic which is emitted if and when we realize /// that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in CUDA device code. /// if (CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget()) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder CUDADiagIfDeviceCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// Same as CUDADiagIfDeviceCode, with "host" and "device" switched. SemaDiagnosticBuilder CUDADiagIfHostCode(SourceLocation Loc, unsigned DiagID); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the device, emits the diagnostics immediately. /// - If CurContext is a non-`declare target` function and we are compiling /// for the device, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPDeviceCode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPDeviceCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as host code". /// /// - If CurContext is a `declare target` function or it is known that the /// function is emitted for the host, emits the diagnostics immediately. /// - If CurContext is a non-host function, just ignore it. /// /// Example usage: /// /// // Variable-length arrays are not allowed in NVPTX device code. /// if (diagIfOpenMPHostode(Loc, diag::err_vla_unsupported)) /// return ExprError(); /// // Otherwise, continue parsing as normal. SemaDiagnosticBuilder diagIfOpenMPHostCode(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, unsigned DiagID, FunctionDecl *FD = nullptr); SemaDiagnosticBuilder targetDiag(SourceLocation Loc, const PartialDiagnostic &PD, FunctionDecl *FD = nullptr) { return targetDiag(Loc, PD.getDiagID(), FD) << PD; } /// Check if the type is allowed to be used for the current target. void checkTypeSupport(QualType Ty, SourceLocation Loc, ValueDecl *D = nullptr); 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); enum CUDAVariableTarget { CVT_Device, /// Emitted on device side with a shadow variable on host side CVT_Host, /// Emitted on host side only CVT_Both, /// Emitted on both sides with different addresses CVT_Unified, /// Emitted as a unified address, e.g. managed variables }; /// Determines whether the given variable is emitted on host or device side. CUDAVariableTarget IdentifyCUDATarget(const VarDecl *D); /// Gets the CUDA target for the current context. CUDAFunctionTarget CurrentCUDATarget() { return IdentifyCUDATarget(dyn_cast<FunctionDecl>(CurContext)); } static bool isCUDAImplicitHostDeviceFunction(const FunctionDecl *D); // CUDA function call preference. Must be ordered numerically from // worst to best. enum CUDAFunctionPreference { CFP_Never, // Invalid caller/callee combination. CFP_WrongSide, // Calls from host-device to host or device // function that do not match current compilation // mode. CFP_HostDevice, // Any calls to host/device functions. CFP_SameSide, // Calls from host-device to host or device // function matching current compilation mode. CFP_Native, // host-to-host or device-to-device calls. }; /// Identifies relative preference of a given Caller/Callee /// combination, based on their host/device attributes. /// \param Caller function which needs address of \p Callee. /// nullptr in case of global context. /// \param Callee target function /// /// \returns preference value for particular Caller/Callee combination. CUDAFunctionPreference IdentifyCUDAPreference(const FunctionDecl *Caller, const FunctionDecl *Callee); /// Determines whether Caller may invoke Callee, based on their CUDA /// host/device attributes. Returns false if the call is not allowed. /// /// Note: Will return true for CFP_WrongSide calls. These may appear in /// semantically correct CUDA programs, but only if they're never codegen'ed. bool IsAllowedCUDACall(const FunctionDecl *Caller, const FunctionDecl *Callee) { return IdentifyCUDAPreference(Caller, Callee) != CFP_Never; } /// May add implicit CUDAHostAttr and CUDADeviceAttr attributes to FD, /// depending on FD and the current compilation settings. void maybeAddCUDAHostDeviceAttrs(FunctionDecl *FD, const LookupResult &Previous); /// May add implicit CUDAConstantAttr attribute to VD, depending on VD /// and current compilation settings. void MaybeAddCUDAConstantAttr(VarDecl *VD); public: /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// (CFP_Never), emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed (CFP_WrongSide), creates a deferred diagnostic to /// be emitted if and when the caller is codegen'ed, and returns true. /// /// Will only create deferred diagnostics for a given SourceLocation once, /// so you can safely call this multiple times without generating duplicate /// deferred errors. /// /// - Otherwise, returns true without emitting any diagnostics. bool CheckCUDACall(SourceLocation Loc, FunctionDecl *Callee); void CUDACheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture); /// Set __device__ or __host__ __device__ attributes on the given lambda /// operator() method. /// /// CUDA lambdas by default is host device function unless it has explicit /// host or device attribute. void CUDASetLambdaAttrs(CXXMethodDecl *Method); /// Finds a function in \p Matches with highest calling priority /// from \p Caller context and erases all functions with lower /// calling priority. void EraseUnwantedCUDAMatches( const FunctionDecl *Caller, SmallVectorImpl<std::pair<DeclAccessPair, FunctionDecl *>> &Matches); /// Given a implicit special member, infer its CUDA target from the /// calls it needs to make to underlying base/field special members. /// \param ClassDecl the class for which the member is being created. /// \param CSM the kind of special member. /// \param MemberDecl the special member itself. /// \param ConstRHS true if this is a copy operation with a const object on /// its RHS. /// \param Diagnose true if this call should emit diagnostics. /// \return true if there was an error inferring. /// The result of this call is implicit CUDA target attribute(s) attached to /// the member declaration. bool inferCUDATargetForImplicitSpecialMember(CXXRecordDecl *ClassDecl, CXXSpecialMember CSM, CXXMethodDecl *MemberDecl, bool ConstRHS, bool Diagnose); /// \return true if \p CD can be considered empty according to CUDA /// (E.2.3.1 in CUDA 7.5 Programming guide). bool isEmptyCudaConstructor(SourceLocation Loc, CXXConstructorDecl *CD); bool isEmptyCudaDestructor(SourceLocation Loc, CXXDestructorDecl *CD); // \brief Checks that initializers of \p Var satisfy CUDA restrictions. In // case of error emits appropriate diagnostic and invalidates \p Var. // // \details CUDA allows only empty constructors as initializers for global // variables (see E.2.3.1, CUDA 7.5). The same restriction also applies to all // __shared__ variables whether they are local or not (they all are implicitly // static in CUDA). One exception is that CUDA allows constant initializers // for __constant__ and __device__ variables. void checkAllowedCUDAInitializer(VarDecl *VD); /// Check whether NewFD is a valid overload for CUDA. Emits /// diagnostics and invalidates NewFD if not. void checkCUDATargetOverload(FunctionDecl *NewFD, const LookupResult &Previous); /// Copies target attributes from the template TD to the function FD. void inheritCUDATargetAttrs(FunctionDecl *FD, const FunctionTemplateDecl &TD); /// Returns the name of the launch configuration function. This is the name /// of the function that will be called to configure kernel call, with the /// parameters specified via <<<>>>. std::string getCudaConfigureFuncName() const; /// \name Code completion //@{ /// Describes the context in which code completion occurs. enum ParserCompletionContext { /// Code completion occurs at top-level or namespace context. PCC_Namespace, /// Code completion occurs within a class, struct, or union. PCC_Class, /// Code completion occurs within an Objective-C interface, protocol, /// or category. PCC_ObjCInterface, /// Code completion occurs within an Objective-C implementation or /// category implementation PCC_ObjCImplementation, /// Code completion occurs within the list of instance variables /// in an Objective-C interface, protocol, category, or implementation. PCC_ObjCInstanceVariableList, /// Code completion occurs following one or more template /// headers. PCC_Template, /// Code completion occurs following one or more template /// headers within a class. PCC_MemberTemplate, /// Code completion occurs within an expression. PCC_Expression, /// Code completion occurs within a statement, which may /// also be an expression or a declaration. PCC_Statement, /// Code completion occurs at the beginning of the /// initialization statement (or expression) in a for loop. PCC_ForInit, /// Code completion occurs within the condition of an if, /// while, switch, or for statement. PCC_Condition, /// Code completion occurs within the body of a function on a /// recovery path, where we do not have a specific handle on our position /// in the grammar. PCC_RecoveryInFunction, /// Code completion occurs where only a type is permitted. PCC_Type, /// Code completion occurs in a parenthesized expression, which /// might also be a type cast. PCC_ParenthesizedExpression, /// Code completion occurs within a sequence of declaration /// specifiers within a function, method, or block. PCC_LocalDeclarationSpecifiers }; void CodeCompleteModuleImport(SourceLocation ImportLoc, ModuleIdPath Path); void CodeCompleteOrdinaryName(Scope *S, ParserCompletionContext CompletionContext); void CodeCompleteDeclSpec(Scope *S, DeclSpec &DS, bool AllowNonIdentifiers, bool AllowNestedNameSpecifiers); struct CodeCompleteExpressionData; void CodeCompleteExpression(Scope *S, const CodeCompleteExpressionData &Data); void CodeCompleteExpression(Scope *S, QualType PreferredType, bool IsParenthesized = false); void CodeCompleteMemberReferenceExpr(Scope *S, Expr *Base, Expr *OtherOpBase, SourceLocation OpLoc, bool IsArrow, bool IsBaseExprStatement, QualType PreferredType); void CodeCompletePostfixExpression(Scope *S, ExprResult LHS, QualType PreferredType); void CodeCompleteTag(Scope *S, unsigned TagSpec); void CodeCompleteTypeQualifiers(DeclSpec &DS); void CodeCompleteFunctionQualifiers(DeclSpec &DS, Declarator &D, const VirtSpecifiers *VS = nullptr); void CodeCompleteBracketDeclarator(Scope *S); void CodeCompleteCase(Scope *S); enum class AttributeCompletion { Attribute, Scope, None, }; void CodeCompleteAttribute( AttributeCommonInfo::Syntax Syntax, AttributeCompletion Completion = AttributeCompletion::Attribute, const IdentifierInfo *Scope = nullptr); /// Determines the preferred type of the current function argument, by /// examining the signatures of all possible overloads. /// Returns null if unknown or ambiguous, or if code completion is off. /// /// If the code completion point has been reached, also reports the function /// signatures that were considered. /// /// FIXME: rename to GuessCallArgumentType to reduce confusion. QualType ProduceCallSignatureHelp(Scope *S, Expr *Fn, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceConstructorSignatureHelp(Scope *S, QualType Type, SourceLocation Loc, ArrayRef<Expr *> Args, SourceLocation OpenParLoc); QualType ProduceCtorInitMemberSignatureHelp(Scope *S, Decl *ConstructorDecl, CXXScopeSpec SS, ParsedType TemplateTypeTy, ArrayRef<Expr *> ArgExprs, IdentifierInfo *II, SourceLocation OpenParLoc); void CodeCompleteInitializer(Scope *S, Decl *D); /// Trigger code completion for a record of \p BaseType. \p InitExprs are /// expressions in the initializer list seen so far and \p D is the current /// Designation being parsed. void CodeCompleteDesignator(const QualType BaseType, llvm::ArrayRef<Expr *> InitExprs, const Designation &D); void CodeCompleteAfterIf(Scope *S, bool IsBracedThen); void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool EnteringContext, bool IsUsingDeclaration, QualType BaseType, QualType PreferredType); void CodeCompleteUsing(Scope *S); void CodeCompleteUsingDirective(Scope *S); void CodeCompleteNamespaceDecl(Scope *S); void CodeCompleteNamespaceAliasDecl(Scope *S); void CodeCompleteOperatorName(Scope *S); void CodeCompleteConstructorInitializer( Decl *Constructor, ArrayRef<CXXCtorInitializer *> Initializers); void CodeCompleteLambdaIntroducer(Scope *S, LambdaIntroducer &Intro, bool AfterAmpersand); void CodeCompleteAfterFunctionEquals(Declarator &D); void CodeCompleteObjCAtDirective(Scope *S); void CodeCompleteObjCAtVisibility(Scope *S); void CodeCompleteObjCAtStatement(Scope *S); void CodeCompleteObjCAtExpression(Scope *S); void CodeCompleteObjCPropertyFlags(Scope *S, ObjCDeclSpec &ODS); void CodeCompleteObjCPropertyGetter(Scope *S); void CodeCompleteObjCPropertySetter(Scope *S); void CodeCompleteObjCPassingType(Scope *S, ObjCDeclSpec &DS, bool IsParameter); void CodeCompleteObjCMessageReceiver(Scope *S); void CodeCompleteObjCSuperMessage(Scope *S, SourceLocation SuperLoc, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression); void CodeCompleteObjCClassMessage(Scope *S, ParsedType Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, bool IsSuper = false); void CodeCompleteObjCInstanceMessage(Scope *S, Expr *Receiver, ArrayRef<IdentifierInfo *> SelIdents, bool AtArgumentExpression, ObjCInterfaceDecl *Super = nullptr); void CodeCompleteObjCForCollection(Scope *S, DeclGroupPtrTy IterationVar); void CodeCompleteObjCSelector(Scope *S, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCProtocolReferences( ArrayRef<IdentifierLocPair> Protocols); void CodeCompleteObjCProtocolDecl(Scope *S); void CodeCompleteObjCInterfaceDecl(Scope *S); void CodeCompleteObjCSuperclass(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationDecl(Scope *S); void CodeCompleteObjCInterfaceCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCImplementationCategory(Scope *S, IdentifierInfo *ClassName, SourceLocation ClassNameLoc); void CodeCompleteObjCPropertyDefinition(Scope *S); void CodeCompleteObjCPropertySynthesizeIvar(Scope *S, IdentifierInfo *PropertyName); void CodeCompleteObjCMethodDecl(Scope *S, Optional<bool> IsInstanceMethod, ParsedType ReturnType); void CodeCompleteObjCMethodDeclSelector(Scope *S, bool IsInstanceMethod, bool AtParameterName, ParsedType ReturnType, ArrayRef<IdentifierInfo *> SelIdents); void CodeCompleteObjCClassPropertyRefExpr(Scope *S, IdentifierInfo &ClassName, SourceLocation ClassNameLoc, bool IsBaseExprStatement); void CodeCompletePreprocessorDirective(bool InConditional); void CodeCompleteInPreprocessorConditionalExclusion(Scope *S); void CodeCompletePreprocessorMacroName(bool IsDefinition); void CodeCompletePreprocessorExpression(); void CodeCompletePreprocessorMacroArgument(Scope *S, IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned Argument); void CodeCompleteIncludedFile(llvm::StringRef Dir, bool IsAngled); void CodeCompleteNaturalLanguage(); void CodeCompleteAvailabilityPlatformName(); void GatherGlobalCodeCompletions(CodeCompletionAllocator &Allocator, CodeCompletionTUInfo &CCTUInfo, SmallVectorImpl<CodeCompletionResult> &Results); //@} //===--------------------------------------------------------------------===// // Extra semantic analysis beyond the C type system public: SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const; private: void CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr, const ArraySubscriptExpr *ASE=nullptr, bool AllowOnePastEnd=true, bool IndexNegated=false); void CheckArrayAccess(const Expr *E); // Used to grab the relevant information from a FormatAttr and a // FunctionDeclaration. struct FormatStringInfo { unsigned FormatIdx; unsigned FirstDataArg; bool HasVAListArg; }; static bool getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember, FormatStringInfo *FSI); bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation loc, ArrayRef<const Expr *> Args); bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall, const FunctionProtoType *Proto); bool CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto); void CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType, ArrayRef<const Expr *> Args, const FunctionProtoType *Proto, SourceLocation Loc); void CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl, StringRef ParamName, QualType ArgTy, QualType ParamTy); void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef<const Expr *> Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType); void CheckSYCLKernelCall(FunctionDecl *CallerFunc, SourceRange CallLoc, ArrayRef<const Expr *> Args); bool CheckObjCString(Expr *Arg); ExprResult CheckOSLogFormatStringArg(Expr *Arg); ExprResult CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID, CallExpr *TheCall); bool CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); void checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD, CallExpr *TheCall); bool CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall, unsigned MaxWidth); bool CheckNeonBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckARMCoprocessorImmediate(const TargetInfo &TI, const Expr *CoprocArg, bool WantCDE); bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall); bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinGatherScatterScale(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall); bool CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall, ArrayRef<int> ArgNums); bool CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall); bool CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum); bool CheckRISCVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall); bool CheckIntelFPGARegBuiltinFunctionCall(unsigned BuiltinID, CallExpr *Call); bool CheckIntelFPGAMemBuiltinFunctionCall(CallExpr *Call); bool SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinVAStartARMMicrosoft(CallExpr *Call); bool SemaBuiltinUnorderedCompare(CallExpr *TheCall); bool SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs); bool SemaBuiltinComplex(CallExpr *TheCall); bool SemaBuiltinVSX(CallExpr *TheCall); bool SemaBuiltinOSLogFormat(CallExpr *TheCall); bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum); 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 SemaBuiltinArithmeticFence(CallExpr *TheCall); bool SemaBuiltinAssume(CallExpr *TheCall); bool SemaBuiltinAssumeAligned(CallExpr *TheCall); bool SemaBuiltinLongjmp(CallExpr *TheCall); bool SemaBuiltinSetjmp(CallExpr *TheCall); ExprResult SemaBuiltinAtomicOverloaded(ExprResult TheCallResult); ExprResult SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult); ExprResult SemaAtomicOpsOverloaded(ExprResult TheCallResult, AtomicExpr::AtomicOp Op); ExprResult SemaBuiltinOperatorNewDeleteOverloaded(ExprResult TheCallResult, bool IsDelete); bool SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum, llvm::APSInt &Result); bool SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum, int Low, int High, bool RangeIsError = true); bool SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum, unsigned Multiple); bool SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum); bool SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, int ArgNum, unsigned ArgBits); bool SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall, int ArgNum, unsigned ExpectedFieldNum, bool AllowName); bool SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall); bool SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID, const char *TypeDesc); bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc); bool SemaBuiltinElementwiseMath(CallExpr *TheCall); bool PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall); bool PrepareBuiltinReduceMathOneArgCall(CallExpr *TheCall); // Matrix builtin handling. ExprResult SemaBuiltinMatrixTranspose(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall, ExprResult CallResult); ExprResult SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall, ExprResult CallResult); public: enum FormatStringType { FST_Scanf, FST_Printf, FST_NSString, FST_Strftime, FST_Strfmon, FST_Kprintf, FST_FreeBSDKPrintf, FST_OSTrace, FST_OSLog, FST_Unknown }; static FormatStringType GetFormatStringType(const FormatAttr *Format); bool FormatStringHasSArg(const StringLiteral *FExpr); static bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx); private: bool CheckFormatArguments(const FormatAttr *Format, ArrayRef<const Expr *> Args, bool IsCXXMember, VariadicCallType CallType, SourceLocation Loc, SourceRange Range, llvm::SmallBitVector &CheckedVarArgs); bool CheckFormatArguments(ArrayRef<const Expr *> Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, SourceLocation Loc, SourceRange range, llvm::SmallBitVector &CheckedVarArgs); void CheckAbsoluteValueFunction(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMaxUnsignedZero(const CallExpr *Call, const FunctionDecl *FDecl); void CheckMemaccessArguments(const CallExpr *Call, unsigned BId, IdentifierInfo *FnName); void CheckStrlcpycatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckStrncatArguments(const CallExpr *Call, IdentifierInfo *FnName); void CheckFreeArguments(const CallExpr *E); void CheckReturnValExpr(Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc, bool isObjCMethod = false, const AttrVec *Attrs = nullptr, const FunctionDecl *FD = nullptr); public: void CheckFloatComparison(SourceLocation Loc, Expr *LHS, Expr *RHS); private: void CheckImplicitConversions(Expr *E, SourceLocation CC = SourceLocation()); void CheckBoolLikeConversion(Expr *E, SourceLocation CC); void CheckForIntOverflow(Expr *E); void CheckUnsequencedOperations(const Expr *E); /// Perform semantic checks on a completed expression. This will either /// be a full-expression or a default argument expression. void CheckCompletedExpr(Expr *E, SourceLocation CheckLoc = SourceLocation(), bool IsConstexpr = false); void CheckBitFieldInitialization(SourceLocation InitLoc, FieldDecl *Field, Expr *Init); /// Check if there is a field shadowing. void CheckShadowInheritedFields(const SourceLocation &Loc, DeclarationName FieldName, const CXXRecordDecl *RD, bool DeclIsField = true); /// Check if the given expression contains 'break' or 'continue' /// statement that produces control flow different from GCC. void CheckBreakContinueBinding(Expr *E); /// Check whether receiver is mutable ObjC container which /// attempts to add itself into the container void CheckObjCCircularContainer(ObjCMessageExpr *Message); void CheckTCBEnforcement(const CallExpr *TheCall, const FunctionDecl *Callee); void AnalyzeDeleteExprMismatch(const CXXDeleteExpr *DE); void AnalyzeDeleteExprMismatch(FieldDecl *Field, SourceLocation DeleteLoc, bool DeleteWasArrayForm); public: /// Register a magic integral constant to be used as a type tag. void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull); struct TypeTagData { TypeTagData() {} TypeTagData(QualType Type, bool LayoutCompatible, bool MustBeNull) : Type(Type), LayoutCompatible(LayoutCompatible), MustBeNull(MustBeNull) {} QualType Type; /// If true, \c Type should be compared with other expression's types for /// layout-compatibility. unsigned LayoutCompatible : 1; unsigned MustBeNull : 1; }; /// A pair of ArgumentKind identifier and magic value. This uniquely /// identifies the magic value. typedef std::pair<const IdentifierInfo *, uint64_t> TypeTagMagicValue; private: /// A map from magic value to type information. std::unique_ptr<llvm::DenseMap<TypeTagMagicValue, TypeTagData>> TypeTagForDatatypeMagicValues; /// Peform checks on a call of a function with argument_with_type_tag /// or pointer_with_type_tag attributes. void CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr, const ArrayRef<const Expr *> ExprArgs, SourceLocation CallSiteLoc); /// Check if we are taking the address of a packed field /// as this may be a problem if the pointer value is dereferenced. void CheckAddressOfPackedMember(Expr *rhs); /// The parser's current scope. /// /// The parser maintains this state here. Scope *CurScope; mutable IdentifierInfo *Ident_super; mutable IdentifierInfo *Ident___float128; /// Nullability type specifiers. IdentifierInfo *Ident__Nonnull = nullptr; IdentifierInfo *Ident__Nullable = nullptr; IdentifierInfo *Ident__Nullable_result = nullptr; IdentifierInfo *Ident__Null_unspecified = nullptr; IdentifierInfo *Ident_NSError = nullptr; /// The handler for the FileChanged preprocessor events. /// /// Used for diagnostics that implement custom semantic analysis for #include /// directives, like -Wpragma-pack. sema::SemaPPCallbacks *SemaPPCallbackHandler; protected: friend class Parser; friend class InitializationSequence; friend class ASTReader; friend class ASTDeclReader; friend class ASTWriter; public: /// Retrieve the keyword associated IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability); /// The struct behind the CFErrorRef pointer. RecordDecl *CFError = nullptr; bool isCFError(RecordDecl *D); /// Retrieve the identifier "NSError". IdentifierInfo *getNSErrorIdent(); /// Retrieve the parser's current scope. /// /// This routine must only be used when it is certain that semantic analysis /// and the parser are in precisely the same context, which is not the case /// when, e.g., we are performing any kind of template instantiation. /// Therefore, the only safe places to use this scope are in the parser /// itself and in routines directly invoked from the parser and *never* from /// template substitution or instantiation. Scope *getCurScope() const { return CurScope; } void incrementMSManglingNumber() const { return CurScope->incrementMSManglingNumber(); } IdentifierInfo *getSuperIdentifier() const; IdentifierInfo *getFloat128Identifier() const; Decl *getObjCDeclContext() const; DeclContext *getCurLexicalContext() const { return OriginalLexicalContext ? OriginalLexicalContext : CurContext; } const DeclContext *getCurObjCLexicalContext() const { const DeclContext *DC = getCurLexicalContext(); // A category implicitly has the attribute of the interface. if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(DC)) DC = CatD->getClassInterface(); return DC; } /// Determine the number of levels of enclosing template parameters. This is /// only usable while parsing. Note that this does not include dependent /// contexts in which no template parameters have yet been declared, such as /// in a terse function template or generic lambda before the first 'auto' is /// encountered. unsigned getTemplateDepth(Scope *S) const; /// To be used for checking whether the arguments being passed to /// function exceeds the number of parameters expected for it. static bool TooManyArguments(size_t NumParams, size_t NumArgs, bool PartialOverloading = false) { // We check whether we're just after a comma in code-completion. if (NumArgs > 0 && PartialOverloading) return NumArgs + 1 > NumParams; // If so, we view as an extra argument. return NumArgs > NumParams; } // Emitting members of dllexported classes is delayed until the class // (including field initializers) is fully parsed. SmallVector<CXXRecordDecl*, 4> DelayedDllExportClasses; SmallVector<CXXMethodDecl*, 4> DelayedDllExportMemberFunctions; private: int ParsingClassDepth = 0; class SavePendingParsedClassStateRAII { public: SavePendingParsedClassStateRAII(Sema &S) : S(S) { swapSavedState(); } ~SavePendingParsedClassStateRAII() { assert(S.DelayedOverridingExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); assert(S.DelayedEquivalentExceptionSpecChecks.empty() && "there shouldn't be any pending delayed exception spec checks"); swapSavedState(); } private: Sema &S; decltype(DelayedOverridingExceptionSpecChecks) SavedOverridingExceptionSpecChecks; decltype(DelayedEquivalentExceptionSpecChecks) SavedEquivalentExceptionSpecChecks; void swapSavedState() { SavedOverridingExceptionSpecChecks.swap( S.DelayedOverridingExceptionSpecChecks); SavedEquivalentExceptionSpecChecks.swap( S.DelayedEquivalentExceptionSpecChecks); } }; /// Helper class that collects misaligned member designations and /// their location info for delayed diagnostics. struct MisalignedMember { Expr *E; RecordDecl *RD; ValueDecl *MD; CharUnits Alignment; MisalignedMember() : E(), RD(), MD(), Alignment() {} MisalignedMember(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment) : E(E), RD(RD), MD(MD), Alignment(Alignment) {} explicit MisalignedMember(Expr *E) : MisalignedMember(E, nullptr, nullptr, CharUnits()) {} bool operator==(const MisalignedMember &m) { return this->E == m.E; } }; /// Small set of gathered accesses to potentially misaligned members /// due to the packed attribute. SmallVector<MisalignedMember, 4> MisalignedMembers; /// Adds an expression to the set of gathered misaligned members. void AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD, CharUnits Alignment); public: /// Diagnoses the current set of gathered accesses. This typically /// happens at full expression level. The set is cleared after emitting the /// diagnostics. void DiagnoseMisalignedMembers(); /// This function checks if the expression is in the sef of potentially /// misaligned members and it is converted to some pointer type T with lower /// or equal alignment requirements. If so it removes it. This is used when /// we do not want to diagnose such misaligned access (e.g. in conversions to /// void*). void DiscardMisalignedMemberAddress(const Type *T, Expr *E); /// This function calls Action when it determines that E designates a /// misaligned member due to the packed attribute. This is used to emit /// local diagnostics like in reference binding. void RefersToMemberWithReducedAlignment( Expr *E, llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action); /// Describes the reason a calling convention specification was ignored, used /// for diagnostics. enum class CallingConventionIgnoredReason { ForThisTarget = 0, VariadicFunction, ConstructorDestructor, BuiltinFunction }; private: // We store SYCL Kernels here and handle separately -- which is a hack. // FIXME: It would be best to refactor this. llvm::SetVector<Decl *> SyclDeviceDecls; // SYCL integration header instance for current compilation unit this Sema // is associated with. std::unique_ptr<SYCLIntegrationHeader> SyclIntHeader; std::unique_ptr<SYCLIntegrationFooter> SyclIntFooter; // We need to store the list of the sycl_kernel functions and their associated // generated OpenCL Kernels so we can go back and re-name these after the // fact. llvm::SmallVector<std::pair<const FunctionDecl *, FunctionDecl *>> SyclKernelsToOpenCLKernels; // Used to suppress diagnostics during kernel construction, since these were // already emitted earlier. Diagnosing during Kernel emissions also skips the // useful notes that shows where the kernel was called. bool DiagnosingSYCLKernel = false; public: void addSyclOpenCLKernel(const FunctionDecl *SyclKernel, FunctionDecl *OpenCLKernel) { SyclKernelsToOpenCLKernels.emplace_back(SyclKernel, OpenCLKernel); } void addSyclDeviceDecl(Decl *d) { SyclDeviceDecls.insert(d); } llvm::SetVector<Decl *> &syclDeviceDecls() { return SyclDeviceDecls; } /// Lazily creates and returns SYCL integration header instance. SYCLIntegrationHeader &getSyclIntegrationHeader() { if (SyclIntHeader == nullptr) SyclIntHeader = std::make_unique<SYCLIntegrationHeader>(*this); return *SyclIntHeader.get(); } SYCLIntegrationFooter &getSyclIntegrationFooter() { if (SyclIntFooter == nullptr) SyclIntFooter = std::make_unique<SYCLIntegrationFooter>(*this); return *SyclIntFooter.get(); } void addSyclVarDecl(VarDecl *VD) { if (LangOpts.SYCLIsDevice && !LangOpts.SYCLIntFooter.empty()) getSyclIntegrationFooter().addVarDecl(VD); } enum SYCLRestrictKind { KernelGlobalVariable, KernelRTTI, KernelNonConstStaticDataVariable, KernelCallVirtualFunction, KernelUseExceptions, KernelCallRecursiveFunction, KernelCallFunctionPointer, KernelAllocateStorage, KernelUseAssembly, KernelCallDllimportFunction, KernelCallVariadicFunction, KernelCallUndefinedFunction, KernelConstStaticVariable }; bool isKnownGoodSYCLDecl(const Decl *D); void checkSYCLDeviceVarDecl(VarDecl *Var); void copySYCLKernelAttrs(const CXXRecordDecl *KernelObj); void ConstructOpenCLKernel(FunctionDecl *KernelCallerFunc, MangleContext &MC); void SetSYCLKernelNames(); void MarkDevices(); /// Get the number of fields or captures within the parsed type. ExprResult ActOnSYCLBuiltinNumFieldsExpr(ParsedType PT); ExprResult BuildSYCLBuiltinNumFieldsExpr(SourceLocation Loc, QualType SourceTy); /// Get a value based on the type of the given field number so that callers /// can wrap it in a decltype() to get the actual type of the field. ExprResult ActOnSYCLBuiltinFieldTypeExpr(ParsedType PT, Expr *Idx); ExprResult BuildSYCLBuiltinFieldTypeExpr(SourceLocation Loc, QualType SourceTy, Expr *Idx); /// Get the number of base classes within the parsed type. ExprResult ActOnSYCLBuiltinNumBasesExpr(ParsedType PT); ExprResult BuildSYCLBuiltinNumBasesExpr(SourceLocation Loc, QualType SourceTy); /// Get a value based on the type of the given base number so that callers /// can wrap it in a decltype() to get the actual type of the base class. ExprResult ActOnSYCLBuiltinBaseTypeExpr(ParsedType PT, Expr *Idx); ExprResult BuildSYCLBuiltinBaseTypeExpr(SourceLocation Loc, QualType SourceTy, Expr *Idx); /// Emit a diagnostic about the given attribute having a deprecated name, and /// also emit a fixit hint to generate the new attribute name. void DiagnoseDeprecatedAttribute(const ParsedAttr &A, StringRef NewScope, StringRef NewName); /// Diagnoses an attribute in the 'intelfpga' namespace and suggests using /// the attribute in the 'intel' namespace instead. void CheckDeprecatedSYCLAttributeSpelling(const ParsedAttr &A, StringRef NewName = ""); /// Creates a SemaDiagnosticBuilder that emits the diagnostic if the current /// context is "used as device code". /// /// - If CurLexicalContext is a kernel function or it is known that the /// function will be emitted for the device, emits the diagnostics /// immediately. /// - If CurLexicalContext is a function and we are compiling /// for the device, but we don't know that this function will be codegen'ed /// for devive yet, creates a diagnostic which is emitted if and when we /// realize that the function will be codegen'ed. /// /// Example usage: /// /// Diagnose __float128 type usage only from SYCL device code if the current /// target doesn't support it /// if (!S.Context.getTargetInfo().hasFloat128Type() && /// S.getLangOpts().SYCLIsDevice) /// SYCLDiagIfDeviceCode(Loc, diag::err_type_unsupported) << "__float128"; SemaDiagnosticBuilder SYCLDiagIfDeviceCode( SourceLocation Loc, unsigned DiagID, DeviceDiagnosticReason Reason = DeviceDiagnosticReason::Sycl | DeviceDiagnosticReason::Esimd); /// Check whether we're allowed to call Callee from the current context. /// /// - If the call is never allowed in a semantically-correct program /// emits an error and returns false. /// /// - If the call is allowed in semantically-correct programs, but only if /// it's never codegen'ed, creates a deferred diagnostic to be emitted if /// and when the caller is codegen'ed, and returns true. /// /// - Otherwise, returns true without emitting any diagnostics. /// /// Adds Callee to DeviceCallGraph if we don't know if its caller will be /// codegen'ed yet. bool checkSYCLDeviceFunction(SourceLocation Loc, FunctionDecl *Callee); /// Finishes analysis of the deferred functions calls that may be not /// properly declared for device compilation. void finalizeSYCLDelayedAnalysis(const FunctionDecl *Caller, const FunctionDecl *Callee, SourceLocation Loc, DeviceDiagnosticReason Reason); /// Tells whether given variable is a SYCL explicit SIMD extension's "private /// global" variable - global variable in the private address space. bool isSYCLEsimdPrivateGlobal(VarDecl *VDecl) { return getLangOpts().SYCLIsDevice && VDecl->hasAttr<SYCLSimdAttr>() && VDecl->hasGlobalStorage() && (VDecl->getType().getAddressSpace() == LangAS::sycl_private); } }; inline Expr *checkMaxWorkSizeAttrExpr(Sema &S, const AttributeCommonInfo &CI, Expr *E) { assert(E && "Attribute must have an argument."); if (!E->isInstantiationDependent()) { llvm::APSInt ArgVal; ExprResult ICE = S.VerifyIntegerConstantExpression(E, &ArgVal); if (ICE.isInvalid()) return nullptr; E = ICE.get(); if (ArgVal.isNegative()) { S.Diag(E->getExprLoc(), diag::warn_attribute_requires_non_negative_integer_argument) << E->getType() << S.Context.UnsignedLongLongTy << E->getSourceRange(); return E; } unsigned Val = ArgVal.getZExtValue(); if (Val == 0) { S.Diag(E->getExprLoc(), diag::err_attribute_argument_is_zero) << CI << E->getSourceRange(); return nullptr; } } return E; } template <typename WorkGroupAttrType> void Sema::addIntelTripleArgAttr(Decl *D, const AttributeCommonInfo &CI, Expr *XDimExpr, Expr *YDimExpr, Expr *ZDimExpr) { assert((XDimExpr && YDimExpr && ZDimExpr) && "argument has unexpected null value"); // Accept template arguments for now as they depend on something else. // We'll get to check them when they eventually get instantiated. if (!XDimExpr->isValueDependent() && !YDimExpr->isValueDependent() && !ZDimExpr->isValueDependent()) { // Save ConstantExpr in semantic attribute XDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, XDimExpr); YDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, YDimExpr); ZDimExpr = checkMaxWorkSizeAttrExpr(*this, CI, ZDimExpr); if (!XDimExpr || !YDimExpr || !ZDimExpr) return; } D->addAttr(::new (Context) WorkGroupAttrType(Context, CI, XDimExpr, YDimExpr, ZDimExpr)); } /// 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; }; template <> void Sema::PragmaStack<Sema::AlignPackInfo>::Act(SourceLocation PragmaLocation, PragmaMsStackAction Action, llvm::StringRef StackSlotLabel, AlignPackInfo Value); } // end namespace clang namespace llvm { // Hash a FunctionDeclAndLoc by looking at both its FunctionDecl and its // SourceLocation. template <> struct DenseMapInfo<clang::Sema::FunctionDeclAndLoc> { using FunctionDeclAndLoc = clang::Sema::FunctionDeclAndLoc; using FDBaseInfo = DenseMapInfo<clang::CanonicalDeclPtr<clang::FunctionDecl>>; static FunctionDeclAndLoc getEmptyKey() { return {FDBaseInfo::getEmptyKey(), clang::SourceLocation()}; } static FunctionDeclAndLoc getTombstoneKey() { return {FDBaseInfo::getTombstoneKey(), clang::SourceLocation()}; } static unsigned getHashValue(const FunctionDeclAndLoc &FDL) { return hash_combine(FDBaseInfo::getHashValue(FDL.FD), FDL.Loc.getHashValue()); } static bool isEqual(const FunctionDeclAndLoc &LHS, const FunctionDeclAndLoc &RHS) { return LHS.FD == RHS.FD && LHS.Loc == RHS.Loc; } }; } // namespace llvm #endif
Feature_matrix.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include <string.h> #include "Feature_matrix.h" void dgemm_(char *TRANSA, char *TRANSB, int *M, int *N, int *K, double *ALPHA, double *A, int *LDA, double *B, int *LDB, double *BETA, double *C, int *LDC); void ComputeFeatureMatrix(int n, int d, int r, double *X, double *w, double *b, double *Z, double sigma) { // Z = cos(X*w+repmat(b,n,1)) * sqrt(2/r) // Assume that memory space for Z has been allocated // Initialize Z as repmat(b,n,1), where b is a row vector of length r int i, j; #pragma omp parallel for private(i, j) for (i = 0; i < n; i++) { for (j = 0; j < r; j++) { Z[i+j*n] = b[j]; } } // Z = X*w + Z double ONE = 1.0; char TRANS_N = 'N'; dgemm_(&TRANS_N, &TRANS_N, &n, &r, &d, &ONE, X, &n, w, &d, &ONE, Z, &n); // Z = cos(Z) * sqrt(2/r) double two = 2; double fac = sqrt(two/r); #pragma omp parallel for private(i) for (i = 0; i < n*r; i++) { Z[i] = cos(Z[i]) * fac; } }
dragon.c
/* * dragon.c * * Created on: 2011-06-26 * Authors: Francis Giraldeau * Pier-Luc St-Onge * * http://en.wikipedia.org/wiki/Dragon_curve */ #define _GNU_SOURCE #include <stdlib.h> #include <time.h> #include <math.h> #include "dragon.h" #include "color.h" xy_t compute_position(int64_t i) { xy_t position; position.x = 0; position.y = 0; if (i > 0) { int64_t mask = 1; int64_t position_y = 1; position.x = 1; position.y = 1; while ((i ^ mask) > mask) { mask <<= 1; position_y -= position.x; position.x += position.y; position.y = position_y; } if (i ^ mask) { xy_t delta = compute_position((mask << 1) - i); position_y -= position.x - delta.x; position.x += position.y - delta.y; position.y = position_y; } } return position; } xy_t compute_orientation(int64_t i) { xy_t orientation; orientation.x = 1; orientation.y = 1; if (i > 0) { int64_t mask = 1; while ((i ^ mask) > mask) { mask <<= 1; } orientation = compute_orientation((mask << 1) - (i + 1)); rotate_right(&orientation); } return orientation; } /* draw dragon in raw matrix */ int dragon_draw_raw(uint64_t start, uint64_t end, char *dragon, int width, int height, limits_t limits, char id) { //printf("start=%" PRId64" end=%"PRId64" id=%d\n", start, end, id); if (end < start) printf("error: start=%"PRId64" > end=%"PRId64"\n", start, end); if (end == start) return 0; xy_t position; xy_t orientation; int i, j; uint64_t n; position = compute_position(start); orientation = compute_orientation(start); // draw dragon position.x -= limits.minimums.x; position.y -= limits.minimums.y; int area = width * height; for (n = start + 1; n <= end; n++) { j = (position.x + (position.x + orientation.x)) >> 1; i = (position.y + (position.y + orientation.y)) >> 1; int index = i * width + j; if (index < 0 || index > area) { printf("index is out of range\n"); return -1; } dragon[index] = id; position.x += orientation.x; position.y += orientation.y; if (((n & -n) << 1) & n) rotate_left(&orientation); else rotate_right(&orientation); } return 0; } void init_canvas(int start, int end, char *canvas, char value) { int i; for (i = start; i < end; i++) { canvas[i] = value; } } void dump_canvas(char *canvas, int width, int height) { int i, j; printf("width=%d height=%d\n", width, height); for (i = 0; i < width; i++) { for (j = 0; j < height; j++) { printf("%d ", canvas[j * width + i]); } printf("\n"); } } void dump_canvas_rgb(struct rgb *canvas, int width, int height) { int i, j; printf("width=%d height=%d\n", width, height); for (i = 0; i < width; i++) { for (j = 0; j < height; j++) { struct rgb *pix = &canvas[j * width + i]; printf("%d %d %d ", pix->r, pix->g, pix->b); } printf("\n"); } } void scale_dragon(int start, int end, struct rgb *image, int image_width, int image_height, char *dragon, int dragon_width, int dragon_height, struct palette *palette) { int i, j, x, y; int scale_x = dragon_width / image_width + 1; int scale_y = dragon_height / image_height + 1; int scale = (scale_x > scale_y ? scale_x : scale_y); int deltaJ = (scale * image_width - dragon_width) / 2; int deltaI = (scale * image_height - dragon_height) / 2; struct rgb *colors = palette->colors; for (y = start; y < end; y++) { int i1 = y * scale - deltaI; int i2 = i1 + scale; if (i1 < 0) i1 = 0; if (i2 > dragon_height) i2 = dragon_height; for (x = 0; x < image_width; x++) { int j1 = x * scale - deltaJ, j2 = j1 + scale; int red = 0; int green = 0; int blue = 0; int cnt = 0; if (j1 < 0) j1 = 0; if (j2 > dragon_width) j2 = dragon_width; for (i = i1; i < i2; i++) { for (j = j1; j < j2; j++) { int id = dragon[i * dragon_width + j]; if (id >= 0) { red += colors[id].r; green += colors[id].g; blue += colors[id].b; } else { red += 255; green += 255; blue += 255; } cnt++; } } int index = y * image_width + x; if (cnt == 0) { image[index] = white; } else { image[index].r = (unsigned char) (red / cnt); image[index].g = (unsigned char) (green / cnt); image[index].b = (unsigned char) (blue / cnt); } } } } int dragon_draw_serial(char **canvas, struct rgb *image, int width, int height, uint64_t size, int nb_colors) { int ret = 0; char *dragon = NULL; struct palette *palette = NULL; limits_t limits; if (dragon_limits_serial(&limits, size, 0) < 0) goto err; int dragon_width = limits.maximums.x - limits.minimums.x; int dragon_height = limits.maximums.y - limits.minimums.y; int area = dragon_width * dragon_height; int m; dragon = (char*)malloc(sizeof(char) * area); if (dragon == NULL) goto err; palette = init_palette(nb_colors); if (palette == NULL) goto err; // clear dragon init_canvas(0, area, dragon, -1); // Draw dragon for (m = 0; m < nb_colors; m++) { uint64_t start = m * size / nb_colors; uint64_t end = (m + 1) * size / nb_colors; dragon_draw_raw(start, end, dragon, dragon_width, dragon_height, limits, m); } // Scale dragon to fit the final image scale_dragon(0, height, image, width, height, dragon, dragon_width, dragon_height, palette); done: free_palette(palette); *canvas = dragon; return ret; err: FREE(dragon); ret = -1; goto done; } int write_img(struct rgb *image, char *file, int width, int height) { FILE *f = NULL; if (image == NULL) return -1; if (file) { if ((f = fopen(file, "wb")) == NULL) { char *msg; if (asprintf(&msg, "Failed to open %s", file) < 0) perror("Failed to open output file"); else perror(msg); return -1; } } fprintf(f, "P6\n%d %d\n%d\n", width, height, 255); fwrite(image, sizeof(struct rgb), width * height, f); fclose(f); return 0; } void dump_limits(limits_t *limits) { if (limits == NULL) return; printf("(%"PRId64",%"PRId64";%"PRId64",%"PRId64")\n", limits->minimums.x, limits->minimums.y, limits->maximums.x, limits->maximums.y); } int cmp_limits(limits_t *l1, limits_t *l2) { if (l1 == NULL || l2 == NULL) return -1; return !(l1->maximums.x == l2->maximums.x && l1->maximums.y == l2->maximums.y && l2->minimums.x == l2->minimums.x && l1->minimums.y == l2->minimums.y); } /* * compare each position exp(i,j) with act(i,j) * return the number of pixels that doesn't match */ int cmp_canvas(char *exp, char *act, int width, int height, int verbose) { int i, j; int sum = 0; int index; if (exp == NULL || act == NULL) return -1; #pragma omp parallel for reduction(+:sum) private(index, j) for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { index = i * width + j; if (exp[index] != act[index]) { if (verbose) printf("pix error (%5d, %5d) expected=%2d actual=%2d\n", j, i, exp[index], act[index]); sum += 1; } } } return sum; } void piece_init(piece_t *piece) { if (piece == NULL) return; piece->position.x = 0; piece->position.y = 0; piece->orientation.x = 1; piece->orientation.y = 1; piece->limits.minimums = piece->position; piece->limits.maximums = piece->position; } int dragon_limits_serial(limits_t *lim, uint64_t nbIterations, __attribute__((unused)) int nb_thread) { piece_t piece; piece_init(&piece); uint64_t start = 0; piece_limit(start, nbIterations, &piece); *lim = piece.limits; return 0; } struct rgb *make_canvas(int width, int height) { int area; area = height * width; if (area <= 0) { return NULL; } return (struct rgb *) malloc(sizeof(struct rgb) * area); } void piece_limit(int64_t start, int64_t end, piece_t *m) { int64_t n; xy_t *position = &m->position; xy_t *orientation = &m->orientation; xy_t *minimums = &m->limits.minimums; xy_t *maximums = &m->limits.maximums; for (n = start + 1; n <= end; n++) { position->x += orientation->x; position->y += orientation->y; if (((n & -n) << 1) & n) rotate_left(orientation); else rotate_right(orientation); if (minimums->x > position->x) minimums->x = position->x; if (minimums->y > position->y) minimums->y = position->y; if (maximums->x < position->x) maximums->x = position->x; if (maximums->y < position->y) maximums->y = position->y; } } /* * merge m2 into m1 * This operation is associative, but not commutative */ void piece_merge(piece_t *m1, piece_t m2) { xy_t orientation; // Initiale orientation of m2 (1,1) xy_t *min1 = &m1->limits.minimums; xy_t *max1 = &m1->limits.maximums; xy_t *min2 = &m2.limits.minimums; xy_t *max2 = &m2.limits.maximums; orientation.x = 1; orientation.y = 1; // Rotate piece #2 while ( orientation.x != m1->orientation.x || orientation.y != m1->orientation.y) { rotate_left(&m2.position); rotate_left(&m2.orientation); limits_invert(&m2.limits); rotate_left(&orientation); } // m2 limits according to m1 min2->x += m1->position.x; min2->y += m1->position.y; max2->x += m1->position.x; max2->y += m1->position.y; // update last segment of m1 m1->position.x += m2.position.x; m1->position.y += m2.position.y; m1->orientation = m2.orientation; // update m1 limits if (min1->x > min2->x) min1->x = min2->x; if (min1->y > min2->y) min1->y = min2->y; if (max1->x < max2->x) max1->x = max2->x; if (max1->y < max2->y) max1->y = max2->y; } void rotate_left(xy_t *xy) { int64_t tmp_y = xy->x; xy->x = -xy->y; xy->y = tmp_y; } void rotate_right(xy_t *xy) { int64_t tmp_y = -xy->x; xy->x = xy->y; xy->y = tmp_y; } void limits_invert(limits_t *limites) { int64_t nouveauMaxY = limites->maximums.x; limites->maximums.x = -limites->minimums.y; limites->minimums.y = limites->minimums.x; limites->minimums.x = -limites->maximums.y; limites->maximums.y = nouveauMaxY; }
GB_binop__rminus_int32.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__rminus_int32) // A.*B function (eWiseMult): GB (_AemultB_01__rminus_int32) // A.*B function (eWiseMult): GB (_AemultB_02__rminus_int32) // A.*B function (eWiseMult): GB (_AemultB_03__rminus_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rminus_int32) // A*D function (colscale): GB (_AxD__rminus_int32) // D*A function (rowscale): GB (_DxB__rminus_int32) // C+=B function (dense accum): GB (_Cdense_accumB__rminus_int32) // C+=b function (dense accum): GB (_Cdense_accumb__rminus_int32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rminus_int32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rminus_int32) // C=scalar+B GB (_bind1st__rminus_int32) // C=scalar+B' GB (_bind1st_tran__rminus_int32) // C=A+scalar GB (_bind2nd__rminus_int32) // C=A'+scalar GB (_bind2nd_tran__rminus_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = (bij - aij) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_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) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (y - x) ; // 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_RMINUS || GxB_NO_INT32 || GxB_NO_RMINUS_INT32) //------------------------------------------------------------------------------ // 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__rminus_int32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rminus_int32) ( 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__rminus_int32) ( 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__rminus_int32) ( 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 int32_t int32_t bwork = (*((int32_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__rminus_int32) ( 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 int32_t *restrict Cx = (int32_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__rminus_int32) ( 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 int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rminus_int32) ( 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__rminus_int32) ( 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__rminus_int32) ( 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__rminus_int32) ( 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__rminus_int32) ( 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__rminus_int32) ( 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 int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_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 ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = (bij - x) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rminus_int32) ( 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 ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = (y - aij) ; } 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) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij - x) ; \ } GrB_Info GB (_bind1st_tran__rminus_int32) ( 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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_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) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (y - aij) ; \ } GrB_Info GB (_bind2nd_tran__rminus_int32) ( 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 int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
hill_paralelo.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> int** reserveMemoryMatrix(int rows, int columns); void fillMatrix(int** matrix, int dimension); void printMatrix(int** matrix, int rows, int columns); char* getAlphabet(); // Functions for read file and get a string clean for encrypt char* readFile(char *filename); void replaceAndremoveSpaces(char* string,char* alphabet); int checkIfExist(char character, char* alphabet); // Function for fill string only if it's necessary char* completeText(char* string, int numberMissingCharacters); // Functions for convert string to vectors of numbers int** separateStringToVectors(char* stringToSeparate, int numberOfVectors, int dimension, char* alphabet); int* convertVectorToNumbers(char* vector, char* alphabet); int* multiplyVector(int** matrix, int *vector, int dimension, int module); char* convertNumbersToStrign(int *vector, char* alphabet, int dimension); char* encryptVector(int** matrix, char * alphabet, int dimension, int numberOfVectors); void printFile(char* fileName, char* string); int main(int argc, char *argv[]){ int dimension, **nonSingularMatrix, *vector, lenghtAlphabet, **matrixOfVectors, module; char *stringToEncrypt, *alphabet, *textEncrypt; int i; if(argc != 2){ printf("numero de parametros incorrecto: program <file>\n"); return 0; } #pragma omp parallel { #pragma omp single { alphabet = getAlphabet(); lenghtAlphabet = strlen(alphabet); } #pragma omp single { printf("Ingresa la dimension de la matriz: "); scanf("%d", &dimension); } #pragma omp single nowait { stringToEncrypt = readFile(argv[1]); } } #pragma omp parallel sections { #pragma omp section { nonSingularMatrix = reserveMemoryMatrix(dimension, dimension); } #pragma omp section { // Removing blank spaces for string to encrypt, pass by value is used replaceAndremoveSpaces(stringToEncrypt,alphabet); } } #pragma omp parallel sections { #pragma omp section fillMatrix(nonSingularMatrix, dimension); #pragma omp section { module = strlen(stringToEncrypt) % dimension; if(module != 0){ // printf("Necesita completarse\n"); int numberMissingCharacters = dimension - module; stringToEncrypt = completeText(stringToEncrypt, numberMissingCharacters); } } } int numberOfVectors = strlen(stringToEncrypt)/dimension; matrixOfVectors = separateStringToVectors(stringToEncrypt, numberOfVectors, dimension, alphabet); #pragma omp parallel for private(i) shared(nonSingularMatrix, matrixOfVectors) firstprivate(dimension, alphabet) for (i = 0; i < numberOfVectors; i++) matrixOfVectors[i] = multiplyVector(nonSingularMatrix, matrixOfVectors[i], dimension, strlen(alphabet)); textEncrypt = encryptVector(matrixOfVectors, alphabet, dimension, numberOfVectors); printFile("salida.txt",textEncrypt); printf("Texto cifrado en archivo salida.txt\n"); return 0; } char* getAlphabet(){ // return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz .,;-!?_"; // return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; return "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; } char* readFile(char *fileName){ char *buffer = NULL; int string_size, read_size; FILE *file = fopen(fileName, "r"); if (file){ // Seek the last byte of the file fseek(file, 0, SEEK_END); // Offset from the first to the last byte, or in other words, filesize string_size = ftell(file); // go back to the start of the file rewind(file); // Allocate a string that can hold it all buffer = (char*) malloc(sizeof(char) * (string_size + 1) ); // Read it all in one operation read_size = fread(buffer, sizeof(char), string_size, file); // fread doesn't set it so put a \0 in the last position // and buffer is now officially a string buffer[string_size] = '\0'; if(string_size != read_size){ // Something went wrong, throw away the memory and set // the buffer to NULL free(buffer); buffer = NULL; } // Always remember to close the file. fclose(file); } return buffer; } int** reserveMemoryMatrix(int rows, int columns){ int **matrix = (int **) calloc(rows, sizeof(int*)); int i; for (i = 0; i < rows; i++) matrix[i] = (int*) calloc(columns, sizeof(int)); return matrix; } void replaceAndremoveSpaces(char* str, char* alphabet) { size_t str_len = strlen(str); char result[str_len]; size_t p = 0; size_t i = 0; for (i = 0; i < str_len; ++i) { if (str[i] != ' ') { if(str[i] == 10 || str[i] == 11 || str[i] == 13 || checkIfExist(str[i], alphabet)){ result[p] = str[i]; }else{ switch((unsigned int)str[i]){ case 165: //Ñ result[p] = 'N'; break; case 164: //ñ result[p] = 'n'; break; default: result[p] = 'X'; } } p++; } } if (p < str_len){ str[p] = '\0'; } for (i = 0; i < p; ++i) { str[i] = result[i]; } } int checkIfExist(char character, char* alphabet){ for (int j = 0; j < strlen(alphabet); j++){ if (character == alphabet[j]){ return 1; } } return 0; } void fillMatrix(int** matrix, int dimension){ int i,j; for (i = 0; i < dimension; i++){ for (j = 0; j < dimension; j++){ printf("Ingresa el elemento [%d][%d] de la matriz: ",i,j); scanf("%d",&matrix[i][j]); } } } char* completeText(char* string, int numberMissingCharacters){ char *new_string = (char*) calloc (strlen(string)+numberMissingCharacters, sizeof(char)); char *complements = (char*) calloc (numberMissingCharacters, sizeof(char)); for (int i = 0; i < numberMissingCharacters; i++) complements[i] = 'X'; strcpy(new_string, string); strcat(new_string, complements); return new_string; } int** separateStringToVectors(char* stringToSeparate, int numberOfVectors, int dimension, char* alphabet){ char **arrayOfStrings; int **matrixOfNumbers; int i,j; arrayOfStrings = (char**) calloc(numberOfVectors, sizeof(char*)); #pragma omp parallel for shared(arrayOfStrings, dimension) private(i) for (i = 0; i < numberOfVectors; i++) arrayOfStrings[i] = (char*) calloc(dimension, sizeof(char)); // Resever memory for matrix containing numbers vectors matrixOfNumbers = reserveMemoryMatrix(numberOfVectors, dimension); // Separate string each 'dimension' elements #pragma omp parallel for private(i,j) shared(arrayOfStrings, stringToSeparate, dimension) for (i = 0; i < numberOfVectors; i++){ for (j = 0; j < dimension; j++){ arrayOfStrings[i][j] = stringToSeparate[(i*dimension)+j]; } } // Convert each string to numbers according to the alphabet #pragma omp parallel for private(i) shared(matrixOfNumbers,arrayOfStrings, alphabet) for (i = 0; i < numberOfVectors; i++) matrixOfNumbers[i] = convertVectorToNumbers(arrayOfStrings[i], alphabet); return matrixOfNumbers; } void printFile(char* fileName, char* string){ FILE * file = fopen(fileName, "w"); if(file){ fputs(string,file); fclose(file); } } int* convertVectorToNumbers(char* vector, char* alphabet){ int* vectorOFNumbers = (int*) calloc(strlen(vector), sizeof(int)); for (int i = 0; i < strlen(vector); i++){ for (int j = 0; j < strlen(alphabet); j++){ if (vector[i] == alphabet[j]){ vectorOFNumbers[i] = j; } } } return vectorOFNumbers; } char* encryptVector(int** matrix, char * alphabet, int dimension, int numberOfVectors){ char* ev = (char*) calloc(dimension*numberOfVectors,sizeof(char)); for(int i=0; i<numberOfVectors; i++){ ev = strcat(ev, convertNumbersToStrign(matrix[i],alphabet,dimension)); } return ev; } char* convertNumbersToStrign(int *vector, char* alphabet, int dimension){ char* str = (char*) calloc(dimension,sizeof(char)); int pos; for(int i = 0 ; i<dimension ; i++){ str[i] = alphabet[vector[i]]; } return str; } int* multiplyVector(int** matrix, int *vector, int dimension, int module){ //Reserving memory for new vector int *resultVector = (int*) calloc(dimension, sizeof(int)); int i, j, tmp; //Iterating the matrix and multiplying by the vector pointer for(i=0; i < dimension; i++) { for(j=0; j < dimension; j++) { *(resultVector + i) += (matrix[i][j] * (*(vector + j))); } // Apply module *(resultVector+i) = *(resultVector+i) % module; } return resultVector; } void printMatrix(int** matrix, int rows, int columns){ for (int i = 0; i < rows; i++){ for (int j = 0; j < columns; j++){ printf("%d ",matrix[i][j]); } printf("\n"); } }
omp-maxof-elements-critical.c
/*********************************************************************************** Example 3.1 : omp-maxof-elements-critical.c Objective : Write an OpenMP program to print Largest of an element in an array This example demonstrates the use of omp_critical section call and PARALLEL For DIRECTIVE Input : Number of threads Number of elements of the array Input is generated by random numbers Output : Each thread checks with its available iterations and finally Master thread prints the maximum value in the array ,Time taken to find the Max Element and also the threads . Created : Aug 2011 Author : RarchK ****************************************************************************/ #include <stdio.h> #include <omp.h> #include <stdlib.h> #include <sys/time.h> #define MAXIMUM 65536 /* Main Program */ main(int argc,char **argv) { int *array, i, Noofelements, cur_max, current_value,Noofthreads; struct timeval TimeValue_Start; struct timezone TimeZone_Start; struct timeval TimeValue_Final; struct timezone TimeZone_Final; long time_start, time_end; double time_overhead; printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Email : RarchK"); printf("\n\t\t---------------------------------------------------------------------------"); printf("\n\t\t Objective : Finding Maximum element of an Array using "); printf("\n\t\t OpenMP Parallel for directive and Critical Section "); printf("\n\t\t..........................................................................\n"); /* Checking for command line arguments */ if( argc != 3 ){ printf("\t\t Very Few Arguments\n "); printf("\t\t Syntax : exec <Threads> <No. of elements> \n"); exit(-1); } Noofthreads=atoi(argv[1]); if ((Noofthreads!=1) && (Noofthreads!=2) && (Noofthreads!=4) && (Noofthreads!=8) && (Noofthreads!= 16) ) { printf("\n Number of threads should be 1,2,4,8 or 16 for the execution of program. \n\n"); exit(-1); } Noofelements=atoi(argv[2]); /* printf("\n\t\t Enter the number of elements\n"); scanf("%d", &Noofelements);*/ if (Noofelements <= 0) { printf("\n\t\t The array elements cannot be stored\n"); exit(1); } printf("\n\t\t Threads : %d ",Noofthreads); printf("\n\t\t Number of elements in Array : %d \n ",Noofelements); /* Dynamic Memory Allocation */ array = (int *) malloc(sizeof(int) * Noofelements); /* Allocating Random Number Values To The Elements Of An Array */ srand(MAXIMUM); for (i = 0; i < Noofelements; i++) array[i] = rand(); if (Noofelements == 1) { printf("\n\t\t The Largest Number In The Array is %d", array[0]); exit(1); } cur_max = 0; gettimeofday(&TimeValue_Start, &TimeZone_Start); /* Set the No. of threads */ omp_set_num_threads(Noofthreads); /* OpenMP Parallel For Directive And Critical Section : Fork a team of threads */ #pragma omp parallel for for (i = 0; i < Noofelements; i = i + 1) { if (array[i] > cur_max) #pragma omp critical if (array[i] > cur_max) cur_max = array[i]; } /* End of the parallel section */ gettimeofday(&TimeValue_Final, &TimeZone_Final); /* calculate the timing for the computation */ time_start = TimeValue_Start.tv_sec * 1000000 + TimeValue_Start.tv_usec; time_end = TimeValue_Final.tv_sec * 1000000 + TimeValue_Final.tv_usec; time_overhead = (time_end - time_start)/1000000.0; /* Serial Calculation */ current_value = array[0]; for (i = 1; i < Noofelements; i++) if (array[i] > current_value) current_value = array[i]; /* Checking For Output Validity */ if (current_value == cur_max) printf("\n\t\t The Max Value Is Same From Serial And Parallel OpenMP Directive\n"); else { printf("\n\t\t The Max Value Is Not Same In Serial And Parallel OpenMP Directive\n"); exit(-1); } /* Freeing Allocated Memory */ printf("\n"); free(array); printf("\n\t\t The Largest Number In The Given Array Is %d\n", cur_max); printf("\n\t\t Time in Seconds (T) : %lf Seconds \n",time_overhead); printf("\n\t\t..........................................................................\n"); }
spmv_int.c
////Example of sparse matrix-vector multiply, using CSR (compressed sparse row format). #include <stdio.h> #include <stdlib.h> #include <string.h> // Add timing support #include <sys/timeb.h> #define REAL int double read_timer() { struct timeb tm; ftime(&tm); return (double) tm.time + (double) tm.millitm / 1000.0; } //#define DEFAULT_DIMSIZE 256 void print_array(char *title, char *name, REAL *A, int n, int m) { printf("%s:\n", title); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%s[%d][%d]:%d ", name, i, j, A[i * m + j]); } printf("\n"); } printf("\n"); } /* subroutine error_check (n,m,alpha,dx,dy,u,f) implicit none ************************************************************ * Checks error between numerical and exact solution * ************************************************************/ int main(int argc, char *argv[]) { int *ia, *ja; REAL *a, *x, *y; int row, i, j, idx, n, nnzMax, nnz, nrows; REAL ts, t, rate; n = 10240; //n = 24; if (argc > 1) n = atoi(argv[1]); nrows = n * n; nnzMax = nrows * 5; ia = (int*)malloc(nrows*sizeof(int)); ja = (int*)malloc(nnzMax*sizeof(int)); a = (REAL*)malloc(nnzMax*sizeof(REAL)); /* Allocate the source and result vectors */ x = (REAL*)malloc(nrows*sizeof(REAL)); y = (REAL*)malloc(nrows*sizeof(REAL)); row = 0; nnz = 0; for (i=0; i<n; i++) { for (j=0; j<n; j++) { ia[row] = nnz; if (i>0) { ja[nnz] = row - n; a[nnz] = -1.0; nnz++; } if (j>0) { ja[nnz] = row - 1; a[nnz] = -1.0; nnz++; } ja[nnz] = row; a[nnz] = 4.0; nnz++; if (j<n-1) { ja[nnz] = row + 1; a[nnz] = -1.0; nnz++; } if (i<n-1) { ja[nnz] = row + n; a[nnz] = -1.0; nnz++; } row++; } } ia[row] = nnz; /* Create the source (x) vector */ for (i=0; i<nrows; i++) x[i] = 1.0; double elapsed = read_timer(); for (row=0; row<nrows; row++) { REAL sum = 0.0; #pragma omp simd reduction(+:sum) for (idx=ia[row]; idx<ia[row+1]; idx++) { sum += a[idx] * x[ja[idx]]; } y[row] = sum; } elapsed = read_timer() - elapsed; printf("seq elasped time(s): %.4f\n", elapsed); int errors = 0; for (row=0; row<nrows; row++) { if (y[row] < 0) { //fprintf(stderr,"y[%d]=%f, fails consistency test\n", row, y[row]); ++errors; } } printf("Errors: %d\n", errors); free(ia); free(ja); free(a); free(x); free(y); return 0; }
sample.c
#include <stdio.h> #include <omp.h> int main(int argc, char *argv[]){ int i; #pragma omp parallel shared(i) { i = omp_get_thread_num(); printf("thread num = %d\n", i); } return 0; }
DRB034-truedeplinear-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* A linear expression is used as array subscription. Data race pair: a[2*i+1]@66:5 vs. a[i]@66:14 */ #include <stdlib.h> int main(int argc, char* argv[]) { int i; int len=2000; if (argc>1) len = atoi(argv[1]); int a[len]; for (i=0; i<len; i++) a[i]=i; #pragma omp parallel for for (i=0;i<len/2;i++) a[2*i+1]=a[i]+1; return 0; }
GB_unop__identity_int16_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_int16_fp32) // op(A') function: GB (_unop_tran__identity_int16_fp32) // C type: int16_t // A type: float // cast: int16_t cij = GB_cast_to_int16_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int16_t z = GB_cast_to_int16_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int16_t z = GB_cast_to_int16_t ((double) (aij)) ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT16 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_int16_fp32) ( int16_t *Cx, // Cx and Ax may be aliased const float *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++) { float aij = Ax [p] ; int16_t z = GB_cast_to_int16_t ((double) (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 ; float aij = Ax [p] ; int16_t z = GB_cast_to_int16_t ((double) (aij)) ; Cx [p] = z ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__identity_int16_fp32) ( 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
ordering_op-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2016 by Contributors * \file ordering_op-inl.h * \brief Function definition of ordering operators */ #ifndef MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #define MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #include <mxnet/operator_util.h> #include <dmlc/optional.h> #include <mshadow/tensor.h> #include <algorithm> #include <vector> #include <string> #include <type_traits> #include "./indexing_op.h" namespace mshadow { template<typename xpu, int src_dim, typename DType, int dst_dim> inline Tensor<xpu, dst_dim, DType> inplace_reshape(const Tensor<xpu, src_dim, DType> &src, const Shape<dst_dim> &target_shape) { CHECK_EQ(src.CheckContiguous(), true); return Tensor<xpu, dst_dim, DType>(src.dptr_, target_shape, src.stream_); } }; namespace mxnet { namespace op { // These enums are only visible within this header namespace topk_enum { enum TopKReturnType {kReturnValue, kReturnIndices, kReturnMask, kReturnBoth}; } // topk_enum struct TopKParam : public dmlc::Parameter<TopKParam> { dmlc::optional<int> axis; int k; int ret_typ; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(TopKParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose the top k indices." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(k).set_default(1) .describe("Number of top elements to select," " should be always smaller than or equal to the element number in the given axis." " A global sort is performed if set k < 1."); DMLC_DECLARE_FIELD(ret_typ).set_default(topk_enum::kReturnIndices) .add_enum("value", topk_enum::kReturnValue) .add_enum("indices", topk_enum::kReturnIndices) .add_enum("mask", topk_enum::kReturnMask) .add_enum("both", topk_enum::kReturnBoth) .describe("The return type.\n" " \"value\" means to return the top k values," " \"indices\" means to return the indices of the top k values," " \"mask\" means to return a mask array containing 0 and 1. 1 means the top k values." " \"both\" means to return a list of both values and indices of top k elements."); DMLC_DECLARE_FIELD(is_ascend).set_default(false) .describe("Whether to choose k largest or k smallest elements." " Top K largest elements will be chosen if set to false."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices when ret_typ is \"indices\" or \"both\". " "An error will be raised if the selected data type cannot precisely represent the " "indices."); } }; struct SortParam : public dmlc::Parameter<SortParam> { dmlc::optional<int> axis; bool is_ascend; DMLC_DECLARE_PARAMETER(SortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s, is_ascend_s; axis_s << axis; is_ascend_s << is_ascend; (*dict)["axis"] = axis_s.str(); (*dict)["is_ascend_s"] = is_ascend_s.str(); } }; struct ArgSortParam : public dmlc::Parameter<ArgSortParam> { dmlc::optional<int> axis; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(ArgSortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices. It is only valid when ret_typ is \"indices\" or" " \"both\". An error will be raised if the selected data type cannot precisely " "represent the indices."); } }; inline void ParseTopKParam(const TShape& src_shape, const TopKParam& param, TShape *target_shape, size_t *pBatch_size = nullptr, index_t *pK = nullptr, index_t *pElement_num = nullptr, int *pAxis = nullptr, bool *do_transpose = nullptr, bool *is_ascend = nullptr) { int axis = 0; size_t batch_size = 1; index_t element_num; if (is_ascend) *is_ascend = param.is_ascend; // get batch_size, axis and element_num if (!static_cast<bool>(param.axis) || src_shape.ndim() == 0) { // No axis given, or scalar element_num = src_shape.Size(); if (do_transpose) *do_transpose = false; } else { axis = param.axis.value(); if (axis < 0) axis += src_shape.ndim(); CHECK(axis >= 0 && axis < static_cast<int>(src_shape.ndim())) << "Invalid axis! axis should be between 0 and " << src_shape.ndim() << ", found axis=" << axis; if ((element_num = src_shape[axis]) != 0) batch_size = src_shape.Size() / element_num; if (do_transpose) *do_transpose = axis != src_shape.ndim() - 1; } // get k const auto k = param.k > 0? param.k : element_num; CHECK(k <= element_num) << "k must be smaller than " << element_num << ", get k = " << k; // get target_shape *target_shape = src_shape; if (param.ret_typ != topk_enum::kReturnMask) { if (static_cast<bool>(param.axis)) (*target_shape)[axis] = k; else *target_shape = mshadow::Shape1(k); } if (pBatch_size) *pBatch_size = batch_size; if (pK) *pK = k; if (pElement_num) *pElement_num = element_num; if (pAxis) *pAxis = axis; } using namespace mshadow; struct fill_ind_to_one { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, DType* out) { out[indices[i]] = static_cast<DType>(1); } }; struct fill_ind { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, const DType* val, int req, DType* out) { KERNEL_ASSIGN(out[indices[i]], req, val[i]); } }; template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<cpu, 1, DType>& dat, const Tensor<cpu, 1, index_t>& ind, const Tensor<cpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<cpu> *s, bool useBatch = true) { // Use full sort when K is relatively large. const bool full_sort(K*8 > N); // Batch size. const index_t M(work.size(0)/(sizeof(DType)*N)); const int omp_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < M; ++i) { // Tensor `work` stores the flattened source data, while `dat` stores the sorted result. DType *vals = reinterpret_cast<DType*>(work.dptr_); DType *sorted_vals = dat.dptr_+i*N; index_t *indices = ind.dptr_+i*N; if (is_ascend) { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } } else { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } } for (index_t j = 0; j < K; ++j) { sorted_vals[j] = vals[indices[j]]; } } } #ifdef __CUDACC__ template<typename DType> MSHADOW_XINLINE bool TopKCompare(DType val1, index_t ind1, DType val2, index_t ind2, bool is_ascend) { // Negative indices denote undefined values which are considered arbitrary small resp. large. return (ind2 < 0) || (ind1 >= 0 && ((is_ascend && val1 < val2) || (!is_ascend && val1 > val2))); } template<typename DType> MSHADOW_XINLINE void MergeTopK(index_t K, DType *val1, index_t *ind1, DType *val2, index_t *ind2, bool is_ascend) { // In-place merge of two sorted top-K lists into val1/ind1. First determine the intervals // [0,..,i1], [0,..i2] of the two lists that will be part of the merged list. index_t i1(K-1), i2(K-1); for (index_t i = 0; i < K; ++i) { if (TopKCompare(val1[i1], ind1[i1], val2[i2], ind2[i2], is_ascend)) { --i2; } else { --i1; } } // Now merge the lists from back to front. for (index_t i = K; i--;) { if (i2 < 0 || i1 >= 0 && TopKCompare(val2[i2], ind2[i2], val1[i1], ind1[i1], is_ascend)) { val1[i] = val1[i1]; ind1[i] = ind1[i1]; --i1; } else { val1[i] = val2[i2]; ind1[i] = ind2[i2]; --i2; } } } template<typename DType> __global__ void PartialSortSmallK(index_t K, index_t N, DType *val, index_t *ind, bool is_ascend) { // Buffer for pairwise reduction. extern __shared__ index_t buff[]; // Start of buffer sections associated with this thread. const index_t offset(threadIdx.x*K); index_t *ind_buff = &buff[offset]; DType *val_buff = reinterpret_cast<DType*>(&buff[blockDim.x*K])+offset; // Initialize top-K values for this thread. for (index_t i = 0; i < K; ++i) { ind_buff[i] = -1; } // Range of values this thread cares about. Each thread block processes // a different batch item (i.e. a different set of ind/val where we // have to select the top-K elements). All threads within the same // block work on the same batch item. const index_t first(blockIdx.x*N+threadIdx.x), last((blockIdx.x+1)*N); // Select top-K from this range and store it sorted in the buffer. // We assume a small K, so linear insertion is o.k. for (index_t i = first; i < last; i += blockDim.x) { DType cur_val(val[i]); index_t cur_ind(ind[i]); for (index_t j = K; j-- && TopKCompare(cur_val, cur_ind, val_buff[j], ind_buff[j], is_ascend); ) { if (j+1 < K) { val_buff[j+1] = val_buff[j]; ind_buff[j+1] = ind_buff[j]; } val_buff[j] = cur_val; ind_buff[j] = cur_ind; } } // Recursive merge of sorted lists for this thread block. Note that blockDim.x is not // necessary a power of two, therefore the additional checks for last_s. for (index_t s = (blockDim.x+1)/2, last_s = blockDim.x; last_s > 1; last_s = s, s = (s+1)/2) { __syncthreads(); if (threadIdx.x < s && threadIdx.x+s < last_s) { MergeTopK(K, val_buff, ind_buff, val_buff+s*K, ind_buff+s*K, is_ascend); } } // Final updates on master thread. if (threadIdx.x == 0) { for (index_t i = 0; i < K; ++i) { ind[blockIdx.x*N+i] = ind_buff[i]; val[blockIdx.x*N+i] = val_buff[i]; } } } template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<gpu, 1, DType>& dat, const Tensor<gpu, 1, index_t>& ind, const Tensor<gpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<gpu> *s, size_t id_size = 0) { // Use full sort for all but very small K for which we // can do a partial sort entirely within shared memory. const auto full_sort(K > 5); // Batch size. const index_t M(dat.size(0)/N); if (full_sort) { // If id_size != 0, divide workspace into two parts. The first one will store batch ids. Tensor<gpu, 1, char> sort_work(work.dptr_+id_size, Shape1(work.size(0)-id_size), s); mxnet::op::SortByKey(dat, ind, is_ascend, &sort_work, 0, sizeof(DType)*8, M); if (id_size && M > 1) { Tensor<gpu, 1, index_t> batch_id(reinterpret_cast<index_t*>(work.dptr_), Shape1(ind.size(0)), s); // Back to back sorting. Note that mxnet::op::SortByKey is a stable sort. batch_id = ind / N; mxnet::op::SortByKey(batch_id, dat, true, &sort_work); mxnet::op::SortByKey(batch_id, ind, true, &sort_work); } } else { const int nthreads(mshadow::cuda::kBaseThreadNum); PartialSortSmallK<<<M, nthreads, nthreads*K*(sizeof(index_t)+sizeof(DType)), mshadow::Stream<gpu>::GetStream(s)>>> (K, N, dat.dptr_, ind.dptr_, is_ascend); } } #endif template<typename xpu, typename DType> size_t GetMemorySize(const TBlob& src, const size_t batch_size = 1) { const auto srcSize = src.Size(); const auto alignment = std::max(sizeof(DType), sizeof(index_t)); // Temp space needed by the gpu-based full sorts. size_t temp_size = std::max( mxnet::op::SortByKeyWorkspaceSize<DType, index_t, xpu>(srcSize, batch_size), mxnet::op::SortByKeyWorkspaceSize<index_t, DType, xpu>(srcSize, batch_size)); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<index_t, index_t, xpu>(srcSize, batch_size)); // Additional temp space for gpu full sorts for batch ids. temp_size += PadBytes(sizeof(index_t) * srcSize, alignment); // Additional temp space for gpu full sorts for segment offsets if (batch_size > 1) temp_size += PadBytes(sizeof(index_t) * (batch_size + 1), alignment); // Temp space for cpu sorts. return std::max(temp_size, sizeof(DType) * srcSize); } typedef void (*topK_func)(const RunContext &ctx, const std::vector<OpReqType>& req, const TBlob& src, const std::vector<TBlob>& ret, const TopKParam& param, char* workspace_curr_ptr, const size_t temp_size, const Resource *pResource); /*! * \brief Implementation of the TopK operation * \tparam xpu the device type. * \tparam DType type of the output value/mask. * \tparam IDType type of the output indices. * * \param ctx the running context * \param req the operation request types to Forward and Backward * \param src the Source blob * \param ret the destination blobs * \param param the topk parameters * \param workspace_curr_ptr allocated memory * \param temp_size length of allocated memory * \param resource temporary resource handler */ template<typename xpu, typename DType, typename IDType> void TopKImpl(const RunContext &ctx, const std::vector<OpReqType>& req, const TBlob& src, const std::vector<TBlob>& ret, const TopKParam& param, char* workspace_curr_ptr, const size_t temp_size, const Resource *pResource = nullptr) { using namespace mshadow::expr; const auto srcSize = src.Size(); // 0. If input shape is 0-shape, directly return if (!srcSize) return; // 1. Parse and initialize information Stream<xpu> *s = ctx.get_stream<xpu>(); size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &k, &element_num, &axis, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<index_t>()) << "'index_t' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<index_t>() << " elements"; const auto total_size = batch_size * k; const auto retMask = param.ret_typ == topk_enum::kReturnMask; const auto alignment = std::max(sizeof(DType), sizeof(index_t)); const auto size_1 = PadBytes(sizeof(DType) * srcSize, alignment); const auto size_2 = PadBytes(sizeof(index_t) * srcSize, alignment); const auto size_3 = retMask ? PadBytes(sizeof(index_t) * total_size, alignment) : 0; size_t id_size = 0; Tensor<xpu, 1, char> workspace; if (!workspace_curr_ptr) { const auto workspace_size = temp_size + size_1 + size_2 + size_3; workspace = pResource->get_space_typed<xpu, 1, char>(Shape1(workspace_size), s); workspace_curr_ptr = workspace.dptr_; } else { id_size = size_2; } const auto shape1 = Shape1(srcSize); Tensor<xpu, 1, DType>sorted_dat(reinterpret_cast<DType*>(workspace_curr_ptr), shape1, s); Tensor<xpu, 1, index_t> indices(reinterpret_cast<index_t*>(workspace_curr_ptr += size_1), shape1, s); // indices in the original matrix workspace_curr_ptr += size_2 + size_3; Tensor<xpu, 3, DType> dat = src.FlatTo3D<xpu, DType>(axis, axis, s); Tensor<xpu, 1, char> temp_workspace; if (std::is_same<xpu, cpu>::value) { Tensor<xpu, 1, DType> flattened_data; if (do_transpose) { flattened_data = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), shape1, s); flattened_data = reshape(transpose(dat, Shape3(0, 2, 1)), shape1); CHECK_EQ(flattened_data.CheckContiguous(), true); } else { flattened_data = src.FlatTo1D<xpu, DType>(s); } // `temp_workspace` stores the flattened data temp_workspace = Tensor<xpu, 1, char>(reinterpret_cast<char*>(flattened_data.dptr_), Shape1(sizeof(DType)*srcSize), s); CHECK_EQ(temp_workspace.CheckContiguous(), true); } else { if (do_transpose) { sorted_dat = reshape(transpose(dat, Shape3(0, 2, 1)), shape1); } else { sorted_dat = reshape(dat, shape1); } CHECK_EQ(sorted_dat.CheckContiguous(), true); temp_workspace = Tensor<xpu, 1, char>(workspace_curr_ptr, Shape1(temp_size), s); // temp space } mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size * element_num, 1, index_t{0}, index_t{1}, kWriteTo, indices.dptr_); CHECK_EQ(indices.CheckContiguous(), true); // 2. Perform inplace batch sort. // After sorting, each batch in `sorted_dat` will be sorted in the corresponding order // up to the k-th element and the `indices` will contain the corresponding index in `sorted_dat` // `temp_workspace` is used to store the flattened source data for CPU device, and it's used as // a temporal buffer for GPU device. TopKSort(sorted_dat, indices, temp_workspace, k, element_num, is_ascend, s, id_size); // 3. Assign results to the ret blob // When returning indices, only update(modulo) required elements instead of full elements // to avoid redundant calculation. // Cast `ret_indices` from int to real_t could introduce conversion error when the element_num // is large enough. if (retMask) { if (req[0] == kNullOp) return; if (req[0] != kWriteTo) LOG(FATAL) << "req=" << req[0] << " is not supported yet."; Tensor<xpu, 1, index_t> sel_indices(reinterpret_cast<index_t*>(workspace_curr_ptr - size_3), Shape1(total_size), s); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = reshape(slice<1>(inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), Shape1(total_size)); if (do_transpose) { mxnet::TShape src_shape = src.shape_.FlatTo3D(axis); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } Tensor<xpu, 1, DType> ret_mask = ret[0].FlatTo1D<xpu, DType>(s); ret_mask = scalar<DType>(0); mxnet_op::Kernel<fill_ind_to_one, xpu>::Launch(s, total_size, sel_indices.dptr_, ret_mask.dptr_); } else if (param.ret_typ == topk_enum::kReturnIndices) { if (do_transpose) { Tensor<xpu, 3, IDType> ret_indices = ret[0].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, IDType> ret_indices = ret[0].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } else { if (do_transpose) { Tensor<xpu, 3, DType> ret_value = ret[0].FlatTo3D<xpu, DType>(axis, axis, s); Tensor<xpu, 3, IDType> ret_indices = ret[1].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_value, req[0], transpose( slice<2>(inplace_reshape(sorted_dat, Shape3(ret_value.shape_[0], ret_value.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, DType> ret_value = ret[0].get_with_shape<xpu, 2, DType>(Shape2(batch_size, k), s); Tensor<xpu, 2, IDType> ret_indices = ret[1].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_value, req[0], slice<1>(inplace_reshape(sorted_dat, Shape2(batch_size, element_num)), 0, k)); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } } template<typename xpu, typename DType> size_t TopKWorkspaceSize(const TBlob& src, const TopKParam& param, size_t *temp_size_ptr) { size_t batch_size = 0; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &k); const auto temp_size = *temp_size_ptr = GetMemorySize<xpu, DType>(src, batch_size); const auto alignment = std::max(sizeof(DType), sizeof(index_t)); size_t workspace_size = temp_size + PadBytes(sizeof(DType) * src.Size(), alignment) + PadBytes(sizeof(index_t) * src.Size(), alignment); if (param.ret_typ == topk_enum::kReturnMask) workspace_size += PadBytes(sizeof(index_t) * batch_size * k, alignment); return workspace_size; } template<typename xpu> void TopK_Operation(const TopKParam& param, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { // If input shape is 0-shape, directly return const auto src = inputs[0]; if (!src.Size()) return; const bool flag = param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnBoth; const TShape& s = src.shape_; int axis = 0; // axis may not be given if (param.axis) { // axis is given if ((axis = param.axis.value()) < 0) axis += s.ndim(); } const size_t batch_size = s.Size() > 1? s.Size() / s[axis] : 1; topK_func F = nullptr; size_t size = 0; MSHADOW_TYPE_SWITCH(src.type_flag_, DType, { size = GetMemorySize<xpu, DType>(src, batch_size); if (flag) { MSHADOW_TYPE_SWITCH(param.dtype, IDType, F = TopKImpl<xpu, DType, IDType>;) } else { F = TopKImpl<xpu, DType, index_t>; } }); CHECK(F != nullptr) << "TopK function was not defined"; (*F)(ctx.run_ctx, req, src, outputs, param, nullptr, size, &ctx.requested[0]); } template<typename xpu> void TopK(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { TopK_Operation<xpu>(nnvm::get<TopKParam>(attrs.parsed), ctx, inputs, req, outputs); } template<typename xpu> void Sort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; TopK_Operation<xpu>(topk_param, ctx, inputs, req, outputs); } template<typename xpu> void ArgSort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.dtype = param.dtype; topk_param.ret_typ = topk_enum::kReturnIndices; TopK_Operation<xpu>(topk_param, ctx, inputs, req, outputs); } template<typename xpu, typename DType, typename IDType> void TopKBackwardImpl(const OpContext &ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const TopKParam& param) { CHECK_NE(req[0], kWriteInplace); using namespace mshadow::expr; Stream<xpu> *s = ctx.run_ctx.get_stream<xpu>(); CHECK(param.ret_typ == topk_enum::kReturnValue || param.ret_typ == topk_enum::kReturnBoth); size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(outputs[0].shape_, param, &target_shape, &batch_size, &k, &element_num, &axis, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<IDType>()) << "'IDType' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<IDType>() << " elements"; const auto total_size = batch_size * k; Tensor<xpu, 1, index_t> workspace = ctx.requested[0].get_space_typed<xpu, 1, index_t>(Shape1(total_size + batch_size), s); Tensor<xpu, 1, index_t> sel_indices(workspace.dptr_, Shape1(total_size), s); Tensor<xpu, 1, index_t> batch_shift(workspace.dptr_ + total_size, Shape1(batch_size), s); Tensor<xpu, 2, DType> out_grad = inputs[0].get_with_shape<xpu, 2, DType>(Shape2(inputs[0].shape_.Size(), 1), s); Tensor<xpu, 2, DType> in_grad = outputs[0].get_with_shape<xpu, 2, DType>(Shape2(outputs[0].shape_.Size(), 1), s); mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size, 1, index_t{0}, element_num, kWriteTo, batch_shift.dptr_); if (do_transpose) { Tensor<xpu, 1, IDType> indices = inputs[2].FlatTo1D<xpu, IDType>(s); mxnet::TShape src_shape = outputs[0].shape_.FlatTo3D(axis); sel_indices = reshape(transpose( broadcast_to(inplace_reshape(batch_shift, Shape3(src_shape[0], src_shape[2], 1)), mxnet::TShape(Shape3(src_shape[0], src_shape[2], k))), Shape3(0, 2, 1)), Shape1(total_size)); sel_indices += tcast<index_t>(indices); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } else { Tensor<xpu, 2, IDType> indices = inputs[2].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); sel_indices = reshape(tcast<index_t>(indices) + broadcast_to(inplace_reshape(batch_shift, Shape2(batch_size, 1)), mxnet::TShape(Shape2(batch_size, k))), Shape1(total_size)); } CHECK_EQ(sel_indices.CheckContiguous(), true); if (kWriteTo == req[0] || kAddTo == req[0]) { if (kWriteTo == req[0]) { in_grad = scalar<DType>(0); } mxnet_op::Kernel<fill_ind, xpu>::Launch(s, total_size, sel_indices.dptr_, out_grad.dptr_, req[0], in_grad.dptr_); } else { LOG(FATAL) << "Not Implemented!"; } } typedef void (*topKBackward_func)(const OpContext &ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const TopKParam& param); template<typename xpu> void TopKBackward_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); const bool flag = param.ret_typ == topk_enum::kReturnBoth; if (flag || param.ret_typ == topk_enum::kReturnValue) { topKBackward_func F = nullptr; MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { if (flag) { MSHADOW_TYPE_SWITCH(param.dtype, IDType, F = TopKBackwardImpl<xpu, DType, IDType>;) } else { F = TopKBackwardImpl<xpu, DType, index_t>; } }); CHECK(F != nullptr) << "TopK backward function was not defined"; (*F)(ctx, inputs, req, outputs, param); } else { LOG(FATAL) << "Not Implemented"; } } inline uint32_t TopKNumOutputs(const NodeAttrs& attrs) { const auto retType = nnvm::get<TopKParam>(attrs.parsed).ret_typ; return retType == topk_enum::kReturnIndices || retType == topk_enum::kReturnMask? 1 : 2; } inline uint32_t TopKNumVisibleOutputs(const NodeAttrs& attrs) { return nnvm::get<TopKParam>(attrs.parsed).ret_typ == topk_enum::kReturnBoth? 2 : 1; } inline bool AssignTypes(std::vector<int> *in_attrs, std::vector<int> *out_attrs, bool checkIndexType = true) { if (checkIndexType) { CHECK(type_assign(&(*out_attrs)[1], MXNET_USE_INT64_TENSOR_SIZE == 1? mshadow::kInt64 : mshadow::kInt32)) << "Failed to set the type of ret_indices"; } TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return out_attrs->at(0) != -1; } inline bool TopKType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); const size_t in_size = in_attrs->size(); const size_t out_size = out_attrs->size(); CHECK_EQ(in_size, 1); CHECK(out_size == 1 || out_size == 2); // out_attr[0] -> stores value // out_attr[1] -> stores indices bool checkIndexType = false; if (out_size > 1) { checkIndexType = param.ret_typ == topk_enum::kReturnValue; if (!checkIndexType) { CHECK(type_assign(&(*out_attrs)[1], param.dtype)) << "Failed to set the type of ret_indices."; } } if (param.ret_typ == topk_enum::kReturnIndices) { CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices."; return true; } return AssignTypes(in_attrs, out_attrs, checkIndexType); } inline bool TopKShapeImpl(const TopKParam& param, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); const auto flag = param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask; CHECK_EQ(out_attrs->size(), (flag? 1U : 2U)); mxnet::TShape target_shape; ParseTopKParam((*in_attrs)[0], param, &target_shape); SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); if (!flag) { SHAPE_ASSIGN_CHECK(*out_attrs, 1, target_shape); } return true; } inline bool TopKShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); return TopKShapeImpl(param, in_attrs, out_attrs); } inline bool SortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { CHECK_EQ(in_attrs->size(), 1); CHECK_EQ(out_attrs->size(), 2); CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt32)) << "Failed to set the type of ret_indices."; return AssignTypes(in_attrs, out_attrs); } inline bool SortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } inline bool ArgSortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices."; return true; } inline bool ArgSortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnIndices; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_
GB_unaryop__lnot_fp64_fp32.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_fp64_fp32 // op(A') function: GB_tran__lnot_fp64_fp32 // C type: double // A type: float // cast: double cij = (double) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ float #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, x) \ double z = (double) x ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_FP64 || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp64_fp32 ( double *restrict Cx, const float *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_fp64_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
conv_dw_kernel_rv64.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Parts of the following code in this file refs to * https://github.com/Tencent/ncnn/blob/master/src/layer/arm/convolutiondepthwise_5x5.h * Tencent is pleased to support the open source community by making ncnn * available. * * Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the * License at * * https://opensource.org/licenses/BSD-3-Clause */ /* * Copyright (c) 2021, OPEN AI LAB * Author: qtang@openailab.com */ #include "conv_dw_kernel_rv64.h" #include "graph/tensor.h" #include "graph/node.h" #include "graph/graph.h" #include "utility/sys_port.h" #include "utility/float.h" #include "utility/log.h" #include "device/cpu/cpu_node.h" #include "device/cpu/cpu_graph.h" #include "device/cpu/cpu_module.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <math.h> #define max(a, b) ((a) > (b) ? (a) : (b)) #define min(a, b) ((a) < (b) ? (a) : (b)) static void relu(float* data, int size, int activation) { for (int i = 0; i < size; i++) { data[i] = max(data[i], (float)0); if (activation > 0) { data[i] = min(data[i], (float)activation); } } } static void pad(float* input, float* output, int in_h, int in_w, int out_h, int out_w, int top, int left, float v) { float* ptr = input; float* outptr = output; int y = 0; // fill top for (; y < top; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } // fill center for (; y < (top + in_h); y++) { int x = 0; for (; x < left; x++) { outptr[x] = v; } if (in_w < 12) { for (; x < (left + in_w); x++) { outptr[x] = ptr[x - left]; } } else { memcpy(outptr + left, ptr, in_w * sizeof(float)); x += in_w; } for (; x < out_w; x++) { outptr[x] = v; } ptr += in_w; outptr += out_w; } // fill bottom for (; y < out_h; y++) { int x = 0; for (; x < out_w; x++) { outptr[x] = v; } outptr += out_w; } } static void convdw3x3s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; float* outptr2 = outptr + outw; const float bias0 = _bias ? _bias[g] : 0.f; const float* kernel0 = kernel + g * 9; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i + 1 < outh; i += 2) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; float sum2 = bias0; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr = sum; *outptr2 = sum2; r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } } } static void convdw3x3s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; const float* kernel0 = kernel + g * 9; const float bias0 = _bias ? _bias[g] : 0.f; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } } static void convdw5x5s1(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; float* outptr2 = outptr + outw; const float bias0 = _bias ? _bias[g] : 0.f; const float* kernel0 = kernel + g * 25; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; const float* r4 = img0 + w * 4; const float* r5 = img0 + w * 5; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; int i = 0; for (; i + 1 < outh; i += 2) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; float sum2 = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r1[3] * k0[3]; sum2 += r1[4] * k0[4]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r2[3] * k1[3]; sum2 += r2[4] * k1[4]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; sum2 += r3[3] * k2[3]; sum2 += r3[4] * k2[4]; sum2 += r4[0] * k3[0]; sum2 += r4[1] * k3[1]; sum2 += r4[2] * k3[2]; sum2 += r4[3] * k3[3]; sum2 += r4[4] * k3[4]; sum2 += r5[0] * k4[0]; sum2 += r5[1] * k4[1]; sum2 += r5[2] * k4[2]; sum2 += r5[3] * k4[3]; sum2 += r5[4] * k4[4]; *outptr = sum; *outptr2 = sum2; r0++; r1++; r2++; r3++; r4++; r5++; outptr++; outptr2++; } r0 += 4 + w; r1 += 4 + w; r2 += 4 + w; r3 += 4 + w; r4 += 4 + w; r5 += 4 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; *outptr = sum; r0++; r1++; r2++; r3++; r4++; outptr++; } r0 += 4; r1 += 4; r2 += 4; r3 += 4; r4 += 4; } } } static void convdw5x5s2(float* output, float* input, float* _kernel, float* _bias, int channel, int in_h, int in_w, int out_h, int out_w, int num_thread) { int w = in_w; int h = in_h; int c_step_in = w * h; int outw = out_w; int outh = out_h; int c_step_out = outw * outh; const int group = channel; const int tailstep = w - 2 * outw + w; const float* kernel = _kernel; #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* out = output + g * c_step_out; float* outptr = out; const float* kernel0 = kernel + g * 25; const float bias0 = _bias ? _bias[g] : 0.f; const float* img0 = input + g * c_step_in; const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w * 2; const float* r3 = img0 + w * 3; const float* r4 = img0 + w * 4; const float* k0 = kernel0; const float* k1 = kernel0 + 5; const float* k2 = kernel0 + 10; const float* k3 = kernel0 + 15; const float* k4 = kernel0 + 20; int i = 0; for (; i < outh; i++) { int remain = outw; for (; remain > 0; remain--) { float sum = bias0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r0[3] * k0[3]; sum += r0[4] * k0[4]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r1[3] * k1[3]; sum += r1[4] * k1[4]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum += r2[3] * k2[3]; sum += r2[4] * k2[4]; sum += r3[0] * k3[0]; sum += r3[1] * k3[1]; sum += r3[2] * k3[2]; sum += r3[3] * k3[3]; sum += r3[4] * k3[4]; sum += r4[0] * k4[0]; sum += r4[1] * k4[1]; sum += r4[2] * k4[2]; sum += r4[3] * k4[3]; sum += r4[4] * k4[4]; *outptr = sum; r0 += 2; r1 += 2; r2 += 2; r3 += 2; r4 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; r4 += tailstep; } } } int conv_dw_run(struct tensor* input_tensor, struct tensor* weight_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct conv_priv_info* conv_info, struct conv_param* param, int num_thread, int cpu_affinity) { float* input = (float*)input_tensor->data; float* output = (float*)output_tensor->data; float* kernel = (float*)weight_tensor->data; float* biases = NULL; if (bias_tensor) biases = (float*)bias_tensor->data; int batch_number = input_tensor->dims[0]; int inc = input_tensor->dims[1]; int inh = input_tensor->dims[2]; int inw = input_tensor->dims[3]; int in_chw = inc * inh * inw; int outc = output_tensor->dims[1]; int outh = output_tensor->dims[2]; int outw = output_tensor->dims[3]; int out_hw = outh * outw; int out_chw = out_hw * outc; int ksize_h = param->kernel_h; int ksize_w = param->kernel_w; int pad_w = param->pad_w0; int pad_h = param->pad_h0; int stride_w = param->stride_w; int stride_h = param->stride_h; int dilation_w = param->dilation_w; int dilation_h = param->dilation_h; int group = param->group; int activation = param->activation; /* pading */ int inh_tmp = inh + pad_h + pad_h; int inw_tmp = inw + pad_w + pad_w; float* input_tmp = NULL; if (inh_tmp == inh && inw_tmp == inw) input_tmp = input; else { input_tmp = (float*)sys_malloc(inh_tmp * inw_tmp * group * sizeof(float)); #pragma omp parallel for num_threads(num_thread) for (int g = 0; g < group; g++) { float* pad_in = input + g * inh * inw; float* pad_out = input_tmp + g * inh_tmp * inw_tmp; pad(pad_in, pad_out, inh, inw, inh_tmp, inw_tmp, pad_h, pad_w, 0.f); } } /* process */ for (int i = 0; i < batch_number; i++) { if (ksize_h == 3 && stride_h == 1) convdw3x3s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); else if (ksize_h == 3 && stride_h == 2) convdw3x3s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); else if (ksize_h == 5 && stride_h == 1) convdw5x5s1(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); else if (ksize_h == 5 && stride_h == 2) convdw5x5s2(output, input_tmp, kernel, biases, group, inh_tmp, inw_tmp, outh, outw, num_thread); else TLOG_ERR("convdw %d x %d, s %d not support.\n", ksize_h, ksize_w, stride_h); } /* relu */ if (activation >= 0) relu(output, batch_number * out_chw, activation); if (!(inh_tmp == inh && inw_tmp == inw)) sys_free(input_tmp); return 0; }
omp_sum_strnum_tls.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <omp.h> #include <unistd.h> #include "stdalsp.h" #define LEN_SUM_STR 16 char *sum_strnum(const char *, const char *); int main() { omp_set_num_threads(4); { #pragma omp parallel sections { #pragma omp section { char *x = "1", *y = "3"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); sleep(1); } #pragma omp section { char *x = "4", *y = "4"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); sleep(1); } #pragma omp section { char *x = "1", *y = "5"; char *ret_str = sum_strnum(x, y); pr_out("[T:%d] %s + %s = %s (%p)", omp_get_thread_num(), x, y, ret_str, ret_str); sleep(1); } } } return 0; } char *sum_strnum(const char *s1, const char *s2) { static char tls_str[LEN_SUM_STR]; #pragma omp threadprivate(tls_str) snprintf(tls_str, LEN_SUM_STR, "%d", atoi(s1) + atoi(s2)); return tls_str; }
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] = 8; tile_size[3] = 64; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } 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(max(0,ceild(16*t2-Nz+5,8)),t1),2*t1-2*t2+1);t3<=min(min(min(floord(4*Nt+Ny-9,8),floord(8*t1+Ny+7,8)),floord(16*t2+Ny+3,8)),floord(16*t1-16*t2+Nz+Ny+5,8));t3++) { for (t4=max(max(max(0,ceild(t1-7,8)),ceild(16*t2-Nz-51,64)),ceild(8*t3-Ny-51,64));t4<=min(min(min(min(floord(4*Nt+Nx-9,64),floord(8*t1+Nx+7,64)),floord(16*t2+Nx+3,64)),floord(8*t3+Nx-5,64)),floord(16*t1-16*t2+Nz+Nx+5,64));t4++) { for (t5=max(max(max(max(max(0,ceild(16*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(64*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),2*t3),Nt-1),2*t1+3),4*t2+2),16*t4+14);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(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(64*t4,4*t5+4); ubv=min(64*t4+63,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((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; }
sum_gpu.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main() { double sum = 0; int width = 40000000; #pragma omp target teams distribute parallel for simd map(tofrom:sum) map(to:width) reduction(+:sum) for(int i = 0; i < width; i++) { sum += i; } printf("\nSum = %lf\n",sum); }
GB_unop__log2_fp64_fp64.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__log2_fp64_fp64 // op(A') function: GB_unop_tran__log2_fp64_fp64 // C type: double // A type: double // cast: double cij = aij // unaryop: cij = log2 (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 = log2 (x) ; // casting #define GB_CAST(z, aij) \ double z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ double aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ double z = aij ; \ Cx [pC] = log2 (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_LOG2 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__log2_fp64_fp64 ( double *Cx, // Cx and Ax may be aliased const double *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 (double), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { double aij = Ax [p] ; double z = aij ; Cx [p] = log2 (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 ; double aij = Ax [p] ; double z = aij ; Cx [p] = log2 (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__log2_fp64_fp64 ( 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
private-clauseModificado.c
#include <stdio.h> #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #endif int main(){ int i, n = 7; int a[n], suma; for (i=0; i<n; i++) a[i] = i; suma = 10000; #pragma omp parallel private(suma) { //suma=500; #pragma omp for for (i=0; i<n; i++){ suma = suma + a[i]; printf("thread %d suma a[%d] / ", omp_get_thread_num(), i); } printf("\n* thread %d suma= %d", omp_get_thread_num(), suma); } printf("\n"); }
convolutiondepthwise_3x3_pack4.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convdw3x3s1_pack4_msa(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* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); v4f32 _bias0 = bias ? (v4f32)__msa_ld_w(bias + g * 4, 0) : (v4f32)__msa_fill_w(0); const float* k0 = kernel.row(g); float* outptr0 = out.row(0); float* outptr1 = out.row(1); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); const float* r3 = img0.row(3); v4f32 _k00 = (v4f32)__msa_ld_w(k0, 0); v4f32 _k01 = (v4f32)__msa_ld_w(k0 + 4, 0); v4f32 _k02 = (v4f32)__msa_ld_w(k0 + 4 * 2, 0); v4f32 _k10 = (v4f32)__msa_ld_w(k0 + 4 * 3, 0); v4f32 _k11 = (v4f32)__msa_ld_w(k0 + 4 * 4, 0); v4f32 _k12 = (v4f32)__msa_ld_w(k0 + 4 * 5, 0); v4f32 _k20 = (v4f32)__msa_ld_w(k0 + 4 * 6, 0); v4f32 _k21 = (v4f32)__msa_ld_w(k0 + 4 * 7, 0); v4f32 _k22 = (v4f32)__msa_ld_w(k0 + 4 * 8, 0); int i = 0; for (; i + 1 < outh; i += 2) { int j = 0; for (; j + 1 < outw; j += 2) { v4f32 _sum00 = _bias0; v4f32 _sum01 = _bias0; v4f32 _sum10 = _bias0; v4f32 _sum11 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r03 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k00, _r00); _sum00 = __msa_fmadd_w(_sum00, _k01, _r01); _sum00 = __msa_fmadd_w(_sum00, _k02, _r02); _sum01 = __msa_fmadd_w(_sum01, _k00, _r01); _sum01 = __msa_fmadd_w(_sum01, _k01, _r02); _sum01 = __msa_fmadd_w(_sum01, _k02, _r03); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); v4f32 _r13 = (v4f32)__msa_ld_w(r1 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k10, _r10); _sum00 = __msa_fmadd_w(_sum00, _k11, _r11); _sum00 = __msa_fmadd_w(_sum00, _k12, _r12); _sum01 = __msa_fmadd_w(_sum01, _k10, _r11); _sum01 = __msa_fmadd_w(_sum01, _k11, _r12); _sum01 = __msa_fmadd_w(_sum01, _k12, _r13); _sum10 = __msa_fmadd_w(_sum10, _k00, _r10); _sum10 = __msa_fmadd_w(_sum10, _k01, _r11); _sum10 = __msa_fmadd_w(_sum10, _k02, _r12); _sum11 = __msa_fmadd_w(_sum11, _k00, _r11); _sum11 = __msa_fmadd_w(_sum11, _k01, _r12); _sum11 = __msa_fmadd_w(_sum11, _k02, _r13); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); v4f32 _r23 = (v4f32)__msa_ld_w(r2 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k20, _r20); _sum00 = __msa_fmadd_w(_sum00, _k21, _r21); _sum00 = __msa_fmadd_w(_sum00, _k22, _r22); _sum01 = __msa_fmadd_w(_sum01, _k20, _r21); _sum01 = __msa_fmadd_w(_sum01, _k21, _r22); _sum01 = __msa_fmadd_w(_sum01, _k22, _r23); _sum10 = __msa_fmadd_w(_sum10, _k10, _r20); _sum10 = __msa_fmadd_w(_sum10, _k11, _r21); _sum10 = __msa_fmadd_w(_sum10, _k12, _r22); _sum11 = __msa_fmadd_w(_sum11, _k10, _r21); _sum11 = __msa_fmadd_w(_sum11, _k11, _r22); _sum11 = __msa_fmadd_w(_sum11, _k12, _r23); v4f32 _r30 = (v4f32)__msa_ld_w(r3, 0); v4f32 _r31 = (v4f32)__msa_ld_w(r3 + 4, 0); v4f32 _r32 = (v4f32)__msa_ld_w(r3 + 4 * 2, 0); v4f32 _r33 = (v4f32)__msa_ld_w(r3 + 4 * 3, 0); _sum10 = __msa_fmadd_w(_sum10, _k20, _r30); _sum10 = __msa_fmadd_w(_sum10, _k21, _r31); _sum10 = __msa_fmadd_w(_sum10, _k22, _r32); _sum11 = __msa_fmadd_w(_sum11, _k20, _r31); _sum11 = __msa_fmadd_w(_sum11, _k21, _r32); _sum11 = __msa_fmadd_w(_sum11, _k22, _r33); __msa_st_w((v4i32)_sum00, outptr0, 0); __msa_st_w((v4i32)_sum01, outptr0 + 4, 0); __msa_st_w((v4i32)_sum10, outptr1, 0); __msa_st_w((v4i32)_sum11, outptr1 + 4, 0); outptr0 += 4 * 2; outptr1 += 4 * 2; r0 += 4 * 2; r1 += 4 * 2; r2 += 4 * 2; r3 += 4 * 2; } for (; j < outw; j++) { v4f32 _sum0 = _bias0; v4f32 _sum1 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k00, _r00); _sum0 = __msa_fmadd_w(_sum0, _k01, _r01); _sum0 = __msa_fmadd_w(_sum0, _k02, _r02); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k10, _r10); _sum0 = __msa_fmadd_w(_sum0, _k11, _r11); _sum0 = __msa_fmadd_w(_sum0, _k12, _r12); _sum1 = __msa_fmadd_w(_sum1, _k00, _r10); _sum1 = __msa_fmadd_w(_sum1, _k01, _r11); _sum1 = __msa_fmadd_w(_sum1, _k02, _r12); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k20, _r20); _sum0 = __msa_fmadd_w(_sum0, _k21, _r21); _sum0 = __msa_fmadd_w(_sum0, _k22, _r22); _sum1 = __msa_fmadd_w(_sum1, _k10, _r20); _sum1 = __msa_fmadd_w(_sum1, _k11, _r21); _sum1 = __msa_fmadd_w(_sum1, _k12, _r22); v4f32 _r30 = (v4f32)__msa_ld_w(r3, 0); v4f32 _r31 = (v4f32)__msa_ld_w(r3 + 4, 0); v4f32 _r32 = (v4f32)__msa_ld_w(r3 + 4 * 2, 0); _sum1 = __msa_fmadd_w(_sum1, _k20, _r30); _sum1 = __msa_fmadd_w(_sum1, _k21, _r31); _sum1 = __msa_fmadd_w(_sum1, _k22, _r32); __msa_st_w((v4i32)_sum0, outptr0, 0); __msa_st_w((v4i32)_sum1, outptr1, 0); outptr0 += 4; outptr1 += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; } r0 += 2 * 4 + w * 4; r1 += 2 * 4 + w * 4; r2 += 2 * 4 + w * 4; r3 += 2 * 4 + w * 4; outptr0 += outw * 4; outptr1 += outw * 4; } for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { v4f32 _sum00 = _bias0; v4f32 _sum01 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r03 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k00, _r00); _sum00 = __msa_fmadd_w(_sum00, _k01, _r01); _sum00 = __msa_fmadd_w(_sum00, _k02, _r02); _sum01 = __msa_fmadd_w(_sum01, _k00, _r01); _sum01 = __msa_fmadd_w(_sum01, _k01, _r02); _sum01 = __msa_fmadd_w(_sum01, _k02, _r03); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); v4f32 _r13 = (v4f32)__msa_ld_w(r1 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k10, _r10); _sum00 = __msa_fmadd_w(_sum00, _k11, _r11); _sum00 = __msa_fmadd_w(_sum00, _k12, _r12); _sum01 = __msa_fmadd_w(_sum01, _k10, _r11); _sum01 = __msa_fmadd_w(_sum01, _k11, _r12); _sum01 = __msa_fmadd_w(_sum01, _k12, _r13); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); v4f32 _r23 = (v4f32)__msa_ld_w(r2 + 4 * 3, 0); _sum00 = __msa_fmadd_w(_sum00, _k20, _r20); _sum00 = __msa_fmadd_w(_sum00, _k21, _r21); _sum00 = __msa_fmadd_w(_sum00, _k22, _r22); _sum01 = __msa_fmadd_w(_sum01, _k20, _r21); _sum01 = __msa_fmadd_w(_sum01, _k21, _r22); _sum01 = __msa_fmadd_w(_sum01, _k22, _r23); __msa_st_w((v4i32)_sum00, outptr0, 0); __msa_st_w((v4i32)_sum01, outptr0 + 4, 0); outptr0 += 4 * 2; r0 += 4 * 2; r1 += 4 * 2; r2 += 4 * 2; } for (; j < outw; j++) { v4f32 _sum0 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k00, _r00); _sum0 = __msa_fmadd_w(_sum0, _k01, _r01); _sum0 = __msa_fmadd_w(_sum0, _k02, _r02); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k10, _r10); _sum0 = __msa_fmadd_w(_sum0, _k11, _r11); _sum0 = __msa_fmadd_w(_sum0, _k12, _r12); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k20, _r20); _sum0 = __msa_fmadd_w(_sum0, _k21, _r21); _sum0 = __msa_fmadd_w(_sum0, _k22, _r22); __msa_st_w((v4i32)_sum0, outptr0, 0); outptr0 += 4; r0 += 4; r1 += 4; r2 += 4; } r0 += 2 * 4; r1 += 2 * 4; r2 += 2 * 4; } } } static void convdw3x3s2_pack4_msa(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) * 4; 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); v4f32 _bias0 = bias ? (v4f32)__msa_ld_w(bias + g * 4, 0) : (v4f32)__msa_fill_w(0); const float* k0 = kernel.row(g); float* outptr0 = out; const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); v4f32 _k00 = (v4f32)__msa_ld_w(k0, 0); v4f32 _k01 = (v4f32)__msa_ld_w(k0 + 4, 0); v4f32 _k02 = (v4f32)__msa_ld_w(k0 + 4 * 2, 0); v4f32 _k10 = (v4f32)__msa_ld_w(k0 + 4 * 3, 0); v4f32 _k11 = (v4f32)__msa_ld_w(k0 + 4 * 4, 0); v4f32 _k12 = (v4f32)__msa_ld_w(k0 + 4 * 5, 0); v4f32 _k20 = (v4f32)__msa_ld_w(k0 + 4 * 6, 0); v4f32 _k21 = (v4f32)__msa_ld_w(k0 + 4 * 7, 0); v4f32 _k22 = (v4f32)__msa_ld_w(k0 + 4 * 8, 0); int i = 0; for (; i < outh; i++) { int j = 0; for (; j + 1 < outw; j += 2) { v4f32 _sum00 = _bias0; v4f32 _sum01 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r03 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4f32 _r04 = (v4f32)__msa_ld_w(r0 + 4 * 4, 0); _sum00 = __msa_fmadd_w(_sum00, _k00, _r00); _sum00 = __msa_fmadd_w(_sum00, _k01, _r01); _sum00 = __msa_fmadd_w(_sum00, _k02, _r02); _sum01 = __msa_fmadd_w(_sum01, _k00, _r02); _sum01 = __msa_fmadd_w(_sum01, _k01, _r03); _sum01 = __msa_fmadd_w(_sum01, _k02, _r04); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); v4f32 _r13 = (v4f32)__msa_ld_w(r1 + 4 * 3, 0); v4f32 _r14 = (v4f32)__msa_ld_w(r1 + 4 * 4, 0); _sum00 = __msa_fmadd_w(_sum00, _k10, _r10); _sum00 = __msa_fmadd_w(_sum00, _k11, _r11); _sum00 = __msa_fmadd_w(_sum00, _k12, _r12); _sum01 = __msa_fmadd_w(_sum01, _k10, _r12); _sum01 = __msa_fmadd_w(_sum01, _k11, _r13); _sum01 = __msa_fmadd_w(_sum01, _k12, _r14); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); v4f32 _r23 = (v4f32)__msa_ld_w(r2 + 4 * 3, 0); v4f32 _r24 = (v4f32)__msa_ld_w(r2 + 4 * 4, 0); _sum00 = __msa_fmadd_w(_sum00, _k20, _r20); _sum00 = __msa_fmadd_w(_sum00, _k21, _r21); _sum00 = __msa_fmadd_w(_sum00, _k22, _r22); _sum01 = __msa_fmadd_w(_sum01, _k20, _r22); _sum01 = __msa_fmadd_w(_sum01, _k21, _r23); _sum01 = __msa_fmadd_w(_sum01, _k22, _r24); __msa_st_w((v4i32)_sum00, outptr0, 0); __msa_st_w((v4i32)_sum01, outptr0 + 4, 0); outptr0 += 4 * 2; r0 += 4 * 4; r1 += 4 * 4; r2 += 4 * 4; } for (; j < outw; j++) { v4f32 _sum0 = _bias0; v4f32 _r00 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r01 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r02 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k00, _r00); _sum0 = __msa_fmadd_w(_sum0, _k01, _r01); _sum0 = __msa_fmadd_w(_sum0, _k02, _r02); v4f32 _r10 = (v4f32)__msa_ld_w(r1, 0); v4f32 _r11 = (v4f32)__msa_ld_w(r1 + 4, 0); v4f32 _r12 = (v4f32)__msa_ld_w(r1 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k10, _r10); _sum0 = __msa_fmadd_w(_sum0, _k11, _r11); _sum0 = __msa_fmadd_w(_sum0, _k12, _r12); v4f32 _r20 = (v4f32)__msa_ld_w(r2, 0); v4f32 _r21 = (v4f32)__msa_ld_w(r2 + 4, 0); v4f32 _r22 = (v4f32)__msa_ld_w(r2 + 4 * 2, 0); _sum0 = __msa_fmadd_w(_sum0, _k20, _r20); _sum0 = __msa_fmadd_w(_sum0, _k21, _r21); _sum0 = __msa_fmadd_w(_sum0, _k22, _r22); __msa_st_w((v4i32)_sum0, outptr0, 0); outptr0 += 4; r0 += 4 * 2; r1 += 4 * 2; r2 += 4 * 2; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } } }
DRB053-inneronly1-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. But the inner level loop can be parallelized. */ #include <string.h> int main(int argc,char *argv[]) { int i; int j; double a[20][20]; memset(a,0,(sizeof(a))); #pragma omp parallel for private(i ,j ) for (i = 0; i < 20; i++) #pragma omp parallel for private(j ) for (j = 0; j < 20; j++) a[i][j] = i * 20 + j; for (i = 0; i < 20 -1; i += 1) { #pragma omp parallel for private(j ) for (j = 0; j < 20; j += 1) { a[i][j] += a[i + 1][j]; } } for (i = 0; i < 20; i++) for (j = 0; j < 20; j++) printf("%d\n",a[i][j]); return 0; }
GB_unop__identity_int64_fp32.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_int64_fp32 // op(A') function: GB_unop_tran__identity_int64_fp32 // C type: int64_t // A type: float // cast: int64_t cij = GB_cast_to_int64_t ((double) (aij)) // unaryop: cij = aij #define GB_ATYPE \ float #define GB_CTYPE \ int64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ float aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ int64_t z = GB_cast_to_int64_t ((double) (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ float aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int64_t z = GB_cast_to_int64_t ((double) (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_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int64_fp32 ( int64_t *Cx, // Cx and Ax may be aliased const float *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; int64_t z = GB_cast_to_int64_t ((double) (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_fp32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
logics.c
//int logics[1000]; //another regular array types, not from a parameter list int main() { int logic_or = 0; int i; int logics[1000]; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < 1000; ++i) { logic_or = logic_or || logics[i]; } } return 0; }
sample_task_single_producer.c
#include <omp.h> #include <stdio.h> #include <sys/time.h> int main(int argc, char * argv[]) { int i,num=(argc>1)?atoi(argv[1]):100; int nthreads; struct timeval t_start, t_end; double time; double *a = (double *)malloc(sizeof(double)*num); #pragma omp parallel { nthreads=omp_get_num_threads(); } for(i=0;i<num;i++){ a[i]=i; } gettimeofday(&t_start,NULL); #pragma omp parallel { #pragma omp single { for(i=0;i<num;i++){ #pragma omp task { a[i]*=0.9; } } } } gettimeofday(&t_end,NULL); time=(t_end.tv_sec * 1000000 + t_end.tv_usec) - (t_start.tv_sec * 1000000 + t_start.tv_usec); printf("%d %f\n",nthreads,time/1000000.0); for(i=0;i<num;i++){ if(a[i]!=i*0.9){ printf("a[%d]=%f != %f\n",i,a[i],i*0.9); return 1; } } }
psd.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Photoshop spec @ https://www.adobe.com/devnet-apps/photoshop/fileformatashtml % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #include "coders/coders-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[257], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(Image *image) { switch (image->compose) { case ColorBurnCompositeOp: return(image->endian == LSBEndian ? "vidi" : "idiv"); case ColorDodgeCompositeOp: return(image->endian == LSBEndian ? " vid" : "div "); case ColorizeCompositeOp: return(image->endian == LSBEndian ? "rloc" : "colr"); case DarkenCompositeOp: return(image->endian == LSBEndian ? "krad" : "dark"); case DifferenceCompositeOp: return(image->endian == LSBEndian ? "ffid" : "diff"); case DissolveCompositeOp: return(image->endian == LSBEndian ? "ssid" : "diss"); case ExclusionCompositeOp: return(image->endian == LSBEndian ? "dums" : "smud"); case HardLightCompositeOp: return(image->endian == LSBEndian ? "tiLh" : "hLit"); case HardMixCompositeOp: return(image->endian == LSBEndian ? "xiMh" : "hMix"); case HueCompositeOp: return(image->endian == LSBEndian ? " euh" : "hue "); case LightenCompositeOp: return(image->endian == LSBEndian ? "etil" : "lite"); case LinearBurnCompositeOp: return(image->endian == LSBEndian ? "nrbl" : "lbrn"); case LinearDodgeCompositeOp: return(image->endian == LSBEndian ? "gddl" : "lddg"); case LinearLightCompositeOp: return(image->endian == LSBEndian ? "tiLl" : "lLit"); case LuminizeCompositeOp: return(image->endian == LSBEndian ? " mul" : "lum "); case MultiplyCompositeOp: return(image->endian == LSBEndian ? " lum" : "mul "); case OverlayCompositeOp: return(image->endian == LSBEndian ? "revo" : "over"); case PinLightCompositeOp: return(image->endian == LSBEndian ? "tiLp" : "pLit"); case SaturateCompositeOp: return(image->endian == LSBEndian ? " tas" : "sat "); case ScreenCompositeOp: return(image->endian == LSBEndian ? "nrcs" : "scrn"); case SoftLightCompositeOp: return(image->endian == LSBEndian ? "tiLs" : "sLit"); case VividLightCompositeOp: return(image->endian == LSBEndian ? "tiLv" : "vLit"); case OverCompositeOp: default: return(image->endian == LSBEndian ? "mron" : "norm"); } } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if ((image->alpha_trait != BlendPixelTrait) || (image->colorspace != sRGBColorspace)) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); if (image->alpha_trait != BlendPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->alpha_trait == UndefinedPixelTrait) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,0,0,MagickTrue,exception); if (complete_mask == (Image *) NULL) return(MagickFalse); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=(MagickRealType) background; (void) SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; Quantum *p; ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=(MagickRealType) GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=(char) layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(const Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); } if (image->depth > 16) return(4); if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static StringInfo *ParseImageResourceBlocks(PSDInfo *psd_info,Image *image, const unsigned char *blocks,size_t length) { const unsigned char *p; ssize_t offset; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return((StringInfo *) NULL); profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); SetStringInfoName(profile,"8bim"); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) break; p=PushLongPixel(MSBEndian,p,&count); offset=(ssize_t) count; if (((p+offset) < blocks) || ((p+offset) > (blocks+length))) break; switch (id) { case 0x03ed: { unsigned short resolution; /* Resolution info. */ if (offset < 16) break; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatImageProperty(image,"tiff:XResolution","%*g", GetMagickPrecision(),image->resolution.x); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatImageProperty(image,"tiff:YResolution","%*g", GetMagickPrecision(),image->resolution.y); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((offset > 4) && (*(p+4) == 0)) psd_info->has_merged_image=MagickFalse; p+=offset; break; } default: { p+=offset; break; } } if ((offset & 0x01) != 0) p++; } return(profile); } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline ssize_t ReadPSDString(Image *image,char *p,const size_t length) { ssize_t count; count=ReadBlob(image,length,(unsigned char *) p); if ((count == (ssize_t) length) && (image->endian != MSBEndian)) { char *q; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } return(count); } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; Quantum index; index=pixel; if (packet_size == 1) index=(Quantum) ScaleQuantumToChar(index); index=(Quantum) ConstrainColormapIndex(image,(ssize_t) index, exception); if (type == 0) SetPixelIndex(image,index,q); if ((type == 0) && (channels > 1)) return; color=image->colormap+(ssize_t) GetPixelIndex(image,q); if (type != 0) color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case -3: case 1: { SetPixelGreen(image,pixel,q); break; } case -4: case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const ssize_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; const unsigned char *p; Quantum *q; ssize_t x; size_t packet_size; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else if (packet_size == 2) { unsigned short nibble; p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } else { MagickFloatType nibble; p=PushFloatPixel(MSBEndian,p,&nibble); pixel=ClampToQuantum((MagickRealType) (QuantumRange*nibble)); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=(ssize_t) image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < (ssize_t) number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t row_size; ssize_t count, y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); (void) memset(pixels,0,row_size*sizeof(*pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > (row_size+2048)) /* arbitrary number */ { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static void Unpredict8Bit(const Image *image,unsigned char *pixels, const size_t count,const size_t row_size) { unsigned char *p; size_t length, remaining; p=pixels; remaining=count; while (remaining > 0) { length=image->columns; while (--length) { *(p+1)+=*p; p++; } p++; remaining-=row_size; } } static void Unpredict16Bit(const Image *image,unsigned char *pixels, const size_t count,const size_t row_size) { unsigned char *p; size_t length, remaining; p=pixels; remaining=count; while (remaining > 0) { length=image->columns; while (--length) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; p+=2; } p+=2; remaining-=row_size; } } static void Unpredict32Bit(const Image *image,unsigned char *pixels, unsigned char *output_pixels,const size_t row_size) { unsigned char *p, *q; ssize_t y; size_t offset1, offset2, offset3, remaining; unsigned char *start; offset1=image->columns; offset2=2*offset1; offset3=3*offset1; p=pixels; q=output_pixels; for (y=0; y < (ssize_t) image->rows; y++) { start=p; remaining=row_size; while (--remaining) { *(p+1)+=*p; p++; } p=start; remaining=image->columns; while (remaining--) { *(q++)=*p; *(q++)=*(p+offset1); *(q++)=*(p+offset2); *(q++)=*(p+offset3); p++; } p=start+row_size; } } static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; unsigned char *p; size_t count, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); if ((MagickSizeType) compact_size > GetBlobSize(image)) ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } if (ret == Z_STREAM_END) break; } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { if (packet_size == 1) Unpredict8Bit(image,pixels,count,row_size); else if (packet_size == 2) Unpredict16Bit(image,pixels,count,row_size); else if (packet_size == 4) { unsigned char *output_pixels; output_pixels=(unsigned char *) AcquireQuantumMemory(count, sizeof(*output_pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } Unpredict32Bit(image,pixels,output_pixels,row_size); pixels=(unsigned char *) RelinquishMagickMemory(pixels); pixels=output_pixels; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { (void) SeekBlob(image,(MagickOffsetType) layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { (void) ResetImagePixels(mask,exception); (void) SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, (ssize_t) layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, (ssize_t) layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, (ssize_t) layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } (void) SeekBlob(image,offset+layer_info->channel_info[channel].size-2, SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) (void) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } if (mask != (Image *) NULL) { if (layer_info->mask.image != (Image *) NULL) layer_info->mask.image=DestroyImage(layer_info->mask.image); layer_info->mask.image=mask; } return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info, (size_t) j,compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType CheckPSDChannels(const PSDInfo *psd_info, LayerInfo *layer_info) { int channel_type; ssize_t i; if (layer_info->channels < psd_info->min_channels) return(MagickFalse); channel_type=RedChannel; if (psd_info->min_channels >= 3) channel_type|=(GreenChannel | BlueChannel); if (psd_info->min_channels >= 4) channel_type|=BlackChannel; for (i=0; i < (ssize_t) layer_info->channels; i++) { short type; type=layer_info->channel_info[i].type; if ((i == 0) && (psd_info->mode == IndexedMode) && (type != 0)) return(MagickFalse); if (type == -1) { channel_type|=AlphaChannel; continue; } if (type < -1) continue; if (type == 0) channel_type&=~RedChannel; else if (type == 1) channel_type&=~GreenChannel; else if (type == 2) channel_type&=~BlueChannel; else if (type == 3) channel_type&=~BlackChannel; } if (channel_type == 0) return(MagickTrue); if ((channel_type == AlphaChannel) && (layer_info->channels >= psd_info->min_channels + 1)) return(MagickTrue); return(MagickFalse); } static void AttachPSDLayers(Image *image,LayerInfo *layer_info, ssize_t number_layers) { ssize_t i; ssize_t j; for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers == 0) { layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); return; } for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } static inline MagickBooleanType PSDSkipImage(const PSDInfo *psd_info, const ImageInfo *image_info,const size_t index) { if (psd_info->has_merged_image == MagickFalse) return(MagickFalse); if (image_info->number_scenes == 0) return(MagickFalse); if (index < image_info->scene) return(MagickTrue); if (index > image_info->scene+image_info->number_scenes-1) return(MagickTrue); return(MagickFalse); } static void CheckMergedImageAlpha(const PSDInfo *psd_info,Image *image) { /* The number of layers cannot be used to determine if the merged image contains an alpha channel. So we enable it when we think we should. */ if (((psd_info->mode == GrayscaleMode) && (psd_info->channels > 1)) || ((psd_info->mode == RGBMode) && (psd_info->channels > 3)) || ((psd_info->mode == CMYKMode) && (psd_info->channels > 4))) image->alpha_trait=BlendPixelTrait; } static void ParseAdditionalInfo(LayerInfo *layer_info) { char key[5]; size_t remaining_length; unsigned char *p; unsigned int size; p=GetStringInfoDatum(layer_info->info); remaining_length=GetStringInfoLength(layer_info->info); while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) break; if (LocaleNCompare(key,"luni",sizeof(key)) == 0) { unsigned char *name; unsigned int length; length=(unsigned int) (*p++) << 24; length|=(unsigned int) (*p++) << 16; length|=(unsigned int) (*p++) << 8; length|=(unsigned int) (*p++); if (length * 2 > size - 4) break; if (sizeof(layer_info->name) <= length) break; name=layer_info->name; while (length > 0) { /* Only ASCII strings are supported */ if (*p++ != '\0') break; *name++=*p++; length--; } if (length == 0) *name='\0'; break; } else p+=size; remaining_length-=(size_t) size; } } static MagickSizeType GetLayerInfoSize(const PSDInfo *psd_info,Image *image) { char type[4]; MagickSizeType size; ssize_t count; size=GetPSDSize(psd_info,image); if (size != 0) return(size); (void) ReadBlobLong(image); count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); if ((count == 4) && ((LocaleNCompare(type,"Mt16",4) == 0) || (LocaleNCompare(type,"Mt32",4) == 0) || (LocaleNCompare(type,"Mtrn",4) == 0))) { size=GetPSDSize(psd_info,image); if (size != 0) return(0); image->alpha_trait=BlendPixelTrait; count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) return(0); count=ReadPSDString(image,type,4); } if ((count == 4) && ((LocaleNCompare(type,"Lr16",4) == 0) || (LocaleNCompare(type,"Lr32",4) == 0))) size=GetPSDSize(psd_info,image); return(size); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; ssize_t i; ssize_t count, index, j, number_layers; size=GetLayerInfoSize(psd_info,image); if (size == 0) { CheckMergedImageAlpha(psd_info,image); return(MagickTrue); } layer_info=(LayerInfo *) NULL; number_layers=(ssize_t) ReadBlobSignedShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) memset(layer_info,0,(size_t) number_layers*sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t top, left, bottom, right; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); top=(ssize_t) ReadBlobSignedLong(image); left=(ssize_t) ReadBlobSignedLong(image); bottom=(ssize_t) ReadBlobSignedLong(image); right=(ssize_t) ReadBlobSignedLong(image); if ((right < left) || (bottom < top)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].page.y=top; layer_info[i].page.x=left; layer_info[i].page.width=(size_t) (right-left); layer_info[i].page.height=(size_t) (bottom-top); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); if ((layer_info[i].channel_info[j].type < -4) || (layer_info[i].channel_info[j].type > 4)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"NoSuchImageChannel", image->filename); } layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } if (CheckPSDChannels(psd_info,&layer_info[i]) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,type,4); if ((count != 4) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadPSDString(image,layer_info[i].blendkey,4); if (count != 4) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.x=(ssize_t) ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)-layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) ( ReadBlobSignedLong(image)-layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); ParseAdditionalInfo(&layer_info[i]); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping != MagickFalse) { AttachPSDLayers(image,layer_info,number_layers); return(MagickTrue); } status=MagickTrue; index=0; for (i=0; i < number_layers; i++) { if ((layer_info[i].image == (Image *) NULL) || (PSDSkipImage(psd_info, image_info,++index) != MagickFalse)) { for (j=0; j < (ssize_t) layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, (MagickSizeType) number_layers); if (status == MagickFalse) break; } if (status != MagickFalse) AttachPSDLayers(image,layer_info,number_layers); else layer_info=DestroyLayerInfo(layer_info,number_layers); return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return(ReadPSDLayersInternal(image,image_info,psd_info,MagickFalse, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; ssize_t i; if ((image_info->number_scenes != 0) && (image_info->scene != 0)) return(MagickTrue); compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { ssize_t type; type=i; if ((type == 1) && (psd_info->channels == 2)) type=-1; if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,type,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,type,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,(MagickOffsetType) i, psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; ssize_t i; size_t image_list_length; ssize_t count; StringInfo *profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count != 4) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels < 1) ThrowReaderException(CorruptImageError,"MissingImageChannel"); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16) && (psd_info.depth != 32)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if ((psd_info.mode == IndexedMode) && (psd_info.channels > 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); if (EOFBlob(image) != MagickFalse) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); status=ResetImagePixels(image,exception); if (status == MagickFalse) return(DestroyImageList(image)); psd_info.min_channels=3; switch (psd_info.mode) { case LabMode: { (void) SetImageColorspace(image,LabColorspace,exception); break; } case CMYKMode: { psd_info.min_channels=4; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } case BitmapMode: case GrayscaleMode: case DuotoneMode: { if (psd_info.depth != 32) { status=AcquireImageColormap(image,MagickMin((size_t) (psd_info.depth < 16 ? 256 : 65536), MaxColormapSize),exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); } psd_info.min_channels=1; (void) SetImageColorspace(image,GRAYColorspace,exception); break; } case IndexedMode: { psd_info.min_channels=1; break; } case MultichannelMode: { if ((psd_info.channels > 0) && (psd_info.channels < 3)) { psd_info.min_channels=psd_info.channels; (void) SetImageColorspace(image,GRAYColorspace,exception); } break; } } if (psd_info.channels < psd_info.min_channels) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if ((psd_info.mode == IndexedMode) && (length < 3)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if ((psd_info.mode == DuotoneMode) || (psd_info.depth == 32)) { /* Duotone image data; the format of this data is undocumented. 32 bits per pixel; the colormap is ignored. */ (void) SeekBlob(image,(const MagickOffsetType) length,SEEK_CUR); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=(size_t) length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=(MagickRealType) ScaleCharToQuantum( (unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); psd_info.has_merged_image=MagickTrue; profile=(StringInfo *) NULL; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } profile=ParseImageResourceBlocks(&psd_info,image,blocks,(size_t) length); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (psd_info.has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ (void) SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (EOFBlob(image) != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"UnexpectedEndOfFile"); } if (image_info->ping != MagickFalse) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); image_list_length=GetImageListLength(image); if ((psd_info.has_merged_image != MagickFalse) || (image_list_length == 1)) psd_info.has_merged_image=(MagickBooleanType) ReadPSDMergedImage( image_info,image,&psd_info,exception); if ((psd_info.has_merged_image == MagickFalse) && (image_list_length == 1) && (length != 0)) { (void) SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } image_list_length=GetImageListLength(image); } if (psd_info.has_merged_image == MagickFalse) { Image *merged; if (image_list_length == 1) { if (profile != (StringInfo *) NULL) profile=DestroyStringInfo(profile); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } image->background_color.alpha=(MagickRealType) TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(image,exception); merged=MergeImageLayers(image,FlattenLayer,exception); if (merged == (Image *) NULL) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } ReplaceImageInList(&image,merged); } if (profile != (StringInfo *) NULL) { Image *next; i=0; next=image; while (next != (Image *) NULL) { if (PSDSkipImage(&psd_info,image_info,i++) == MagickFalse) (void) SetImageProfile(next,GetStringInfoName(profile),profile, exception); next=next->next; } profile=DestroyStringInfo(profile); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned int) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=WriteBlobMSBLong(image,(unsigned int) size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobLong(image,(unsigned int) size)); return(WriteBlobLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickOffsetType offset) { MagickOffsetType current_offset; ssize_t result; current_offset=TellBlob(image); (void) SeekBlob(image,offset,SEEK_SET); result=SetPSDSize(psd_info,image,size); (void) SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; ssize_t i, j; unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const CompressionType compression, const ssize_t channels) { size_t length; ssize_t i, y; if (compression == RLECompression) { length=(size_t) WriteBlobShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) length=(size_t) WriteBlobShort(image,ZipWithoutPrediction); #endif else length=(size_t) WriteBlobShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, const CompressionType compression,ExceptionInfo *exception) { MagickBooleanType monochrome; QuantumInfo *quantum_info; const Quantum *p; ssize_t i; size_t count, length; ssize_t y; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory( MagickMinBufferExtent,sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } memset(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) MagickMinBufferExtent; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) MagickMinBufferExtent-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { CompressionType compression; Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; compression=next_image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if ((next_image->storage_class != PseudoClass) || (IsImageGray(next_image) != MagickFalse)) { if (IsImageGray(next_image) == MagickFalse) channels=(size_t) (next_image->colorspace == CMYKColorspace ? 4 : 3); if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,compression, (ssize_t) channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if ((next_image->storage_class == PseudoClass) && (IsImageGray(next_image) == MagickFalse)) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,compression, exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,compression, exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=(size_t) WriteBlobShort(image,(const unsigned short) channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) memmove(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12)) && ((ssize_t) length-(cnt+12)-(q-datum)) > 0) { (void) memmove(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(char) (*p++); key[1]=(char) (*p++); key[2]=(char) (*p++); key[3]=(char) (*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) memmove(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); (void) SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,size_t *layers_size, ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; ssize_t i; size_t layer_count, layer_index, length, name_length, rounded_size, size; status=MagickTrue; base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); (void) SetPSDSize(psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobShort(image,-(unsigned short) layer_count); else size+=WriteBlobShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=(unsigned char) (strlen(property) == 9 ? 255 : 0); } size+=WriteBlobSignedLong(image,(signed int) next_image->page.y); size+=WriteBlobSignedLong(image,(signed int) next_image->page.x); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.y+ next_image->rows)); size+=WriteBlobSignedLong(image,(signed int) (next_image->page.x+ next_image->columns)); channels=1; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=(unsigned short) (next_image->colorspace == CMYKColorspace ? 4 : 3); total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(psd_info,image,-2); size+=WriteBlobString(image,image->endian == LSBEndian ? "MIB8" :"8BIM"); size+=WriteBlobString(image,CompositeOperatorToPSDBlendMode(next_image)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,(const unsigned char) (next_image->compose == NoCompositeOp ? 1 << 0x02 : 1)); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobLong(image,20); size+=WriteBlobSignedLong(image,(const signed int) mask->page.y); size+=WriteBlobSignedLong(image,(const signed int) mask->page.x); size+=WriteBlobSignedLong(image,(const signed int) (mask->rows+ mask->page.y)); size+=WriteBlobSignedLong(image,(const signed int) (mask->columns+ mask->page.x)); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,(const unsigned char) (mask->compose == NoCompositeOp ? 2 : 0)); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } /* Write the total size */ if (layers_size != (size_t*) NULL) *layers_size=size; if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) (void) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } return(status); } ModuleExport MagickBooleanType WritePSDLayers(Image * image, const ImageInfo *image_info,const PSDInfo *psd_info,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=WritePolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickTrue); return WritePSDLayersInternal(image,image_info,psd_info,(size_t*) NULL, exception); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { const StringInfo *icc_profile; ImageType type; MagickBooleanType status; PSDInfo psd_info; ssize_t i; size_t length, num_channels, packet_size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ type=IdentifyImageCoderType(image,exception); if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && ((type == GrayscaleType) || (type == BilevelType))) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if ((type == GrayscaleType) || (type == BilevelType)) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if (((type == GrayscaleType) || (type == BilevelType)) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].red))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].green))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(ClampToQuantum( image->colormap[i].blue))); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((ssize_t) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } if (status != MagickFalse) { const char *option; MagickOffsetType size_offset; size_t size; size_offset=TellBlob(image); (void) SetPSDSize(&psd_info,image,0); option=GetImageOption(image_info,"psd:write-layers"); if (IsStringFalse(option) != MagickTrue) { status=WritePSDLayersInternal(image,image_info,&psd_info,&size, exception); (void) WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 12),size_offset); } } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image_info->compression != UndefinedCompression) image->compression=image_info->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
objdetect_prv.c
#include "objdetect_prv.h" float overlap ( float x1, float w1, float x2, float w2 ) { float l1 = x1 - w1/2; float l2 = x2 - w2/2; float left = l1 > l2 ? l1 : l2; float r1 = x1 + w1/2; float r2 = x2 + w2/2; float right = r1 < r2 ? r1 : r2; return right - left; } float box_intersection ( box_struct a, box_struct b ) { float w = overlap(a.x, a.w, b.x, b.w); float h = overlap(a.y, a.h, b.y, b.h); if(w < 0 || h < 0) { return 0; } float area = w * h; return area; } float box_iou ( box_struct a, box_struct b ) { float i = box_intersection(a, b); float u = a.w * a.h + b.w * b.h - i; return i / u; } void softmax ( float *input, float *output, int stride, // l.w * l.h int num_class ) { int i = 0; int j = 0; float* inptr = input; float* outptr = output; for(i = 0; i < stride; ++i) { inptr = input + i; outptr = output + i; float sum = 0; float largest = -FLT_MAX; for(j = 0; j < num_class; ++j) { if(inptr[j * stride] > largest) { largest = inptr[j * stride]; } } for(j = 0; j < num_class; ++j) { float e = exp(inptr[j * stride] - largest); sum += e; outptr[j * stride] = e; } for(j = 0; j < num_class; ++j) { outptr[j * stride] /= sum; } } } void logistic_activate ( float *x, int num ) { int i = 0; for(i = 0; i < num; ++i) { x[i] = 1.0f / (1.0f + exp(-x[i])); } } void relu_activate ( float *x, int num ) { int i = 0; for(i = 0; i < num; ++i) { if(x[i] < 0.0f) { x[i] = 0.0f; } } } void linear_activate ( float *x, int num ) { return; } void leaky_activate ( float *x, int num ) { int i = 0; for(i = 0; i < num; ++i) { if(x[i] < 0.0f) { x[i] = 0.1f * x[i]; } } } void add_bias ( float *output, float *biases, int n, int size ) { int i = 0; int j = 0; for(i = 0; i < n; ++i) { for(j = 0; j < size; ++j) { output[i * size + j] += biases[i]; } } } void scale_bias ( float *output, float *scales, int n, int size ) { int i = 0; int j = 0; for(i = 0; i < n; ++i) { for(j = 0; j < size; ++j) { output[i * size + j] *= scales[i]; } } } void batch_normalize ( float *src, float *mean, float *variance, int filters, int spatial ) { int f = 0; int i = 0; for(f = 0; f < filters; ++f) { for(i = 0; i < spatial; ++i) { int index = f * spatial + i; //TODO: deal with sqrt first src[index] = (src[index] - mean[f]) / (sqrt(variance[f]) + 0.000001f); } } } void gemm ( int M, int N, int K, float *A, float *B, float *C ) { // TODO: try to use some blas library to speed up int i,j,k; //#pragma omp parallel for for(i = 0; i < M; ++i) { for(k = 0; k < K; ++k) { register float A_PART = A[i * K + k]; for(j = 0; j < N; ++j) { C[i * N + j] += A_PART * B[k * N + j]; } } } } float im2col_get_pixel ( float *im, int height, int width, int row, int col, int channel, int pad ) { row -= pad; col -= pad; if (row < 0 || col < 0 || row >= height || col >= width) { return 0; } return im[col + width*(row + height*channel)]; } void im2col ( const float *data_im, const int in_channels, const int in_height, const int in_width, const int ksize, const int pad, const int stride, float *data_col ) { // flatten convolved area into one column int kernel_offset_c = 0; int kernel_offset_h = 0; int kernel_offset_w = 0; int in_offset_h = 0; int in_offset_w = 0; int dst_idx = 0; for (kernel_offset_c = 0; kernel_offset_c < in_channels; ++kernel_offset_c) { for (kernel_offset_h = 0; kernel_offset_h < ksize; ++kernel_offset_h) { for (kernel_offset_w = 0; kernel_offset_w < ksize; ++kernel_offset_w) { for (in_offset_h = 0; in_offset_h < in_height; in_offset_h += stride) { for (in_offset_w = 0; in_offset_w < in_width; in_offset_w += stride) { const int im_h_idx = kernel_offset_h + in_offset_h - pad; const int im_w_idx = kernel_offset_w + in_offset_w - pad; //const int kernel_idx = kernel_offset_c * ksize * ksize + //kernel_offset_h * ksize + kernel_offset_w; //const int dst_idx = kernel_idx * in_height * in_width + //in_offset_h * in_width + in_offset_w; if (im_h_idx < 0 || im_w_idx < 0 || im_h_idx >= in_height || im_w_idx >= in_width) { data_col[dst_idx] = 0.0f; } else { data_col[dst_idx] = data_im[kernel_offset_c * in_width * in_height + im_h_idx * in_width + im_w_idx]; } ++dst_idx; } } } } } } void forward_concat_2d_layer ( layer_struct l, network_struct net ) { int i = 0; const int num_concat = l.concat_index[0]; float *out = l.output; for (i = 0; i < num_concat; ++i) { float *in = net.layers[l.concat_index[i+1]].output; int insize = net.layers[l.concat_index[i+1]].outputs >> 1; memcpy(out, in, insize * sizeof(float)); out += insize; } for (i = 0; i < num_concat; ++i) { float *in = net.layers[l.concat_index[i+1]].output; int insize = net.layers[l.concat_index[i+1]].outputs >> 1; memcpy(out, in + insize, insize * sizeof(float)); out += insize; } } void forward_concat_1d_layer ( layer_struct l, network_struct net ) { int i = 0; const int num_concat = l.concat_index[0]; float *out = l.output; for (i = 0; i < num_concat; ++i) { float *in = net.layers[l.concat_index[i+1]].output; int insize = net.layers[l.concat_index[i+1]].outputs; memcpy(out, in, insize * sizeof(float)); out += insize; } } void forward_route_layer ( layer_struct l, network_struct net ) { float *in = net.layers[l.route_index].output; memcpy(l.output, in, l.outputs * sizeof(float)); } void forward_group_convolutional_layer ( layer_struct l, network_struct net ) { #if NNPACK struct nnp_size input_size = { l.w, l.h }; struct nnp_padding input_padding = { l.pad, l.pad, l.pad, l.pad }; struct nnp_size kernel_size = { l.size, l.size }; struct nnp_size stride = { l.stride, l.stride }; const int filter_num = l.c; const int in_plane_size = l.w * l.h; const int out_plane_size = l.out_w * l.out_h; const int kernel_plane_size = l.size * l.size; int i = 0; for (i = 0; i < filter_num; ++i) { float *inptr = net.input + i * in_plane_size; float *wptr = l.weights + i * kernel_plane_size; float *bptr = l.biases + i; float *outptr = l.output + i * out_plane_size; nnp_convolution_inference ( nnp_convolution_algorithm_implicit_gemm, nnp_convolution_transform_strategy_tuple_based, 1, 1, input_size, input_padding, kernel_size, stride, inptr, wptr, bptr, outptr, NULL, NULL, nnp_activation_relu, NULL, net.threadpool, NULL ); } #else const int NUM_FILTERS = l.c; const int IN_PLANE_SIZE = l.h * l.w; const int M = 1; const int N = l.out_w * l.out_h; const int K = l.size * l.size; int i = 0; for (i = 0; i < NUM_FILTERS; ++i) { float *intputptr = net.input + i * IN_PLANE_SIZE; float *weightptr = l.weights + i * K; float *rearrangedimptr = (float*)alloc_from_stack(N * K * sizeof(float)); float *outptr = l.output + i * N; im2col(intputptr, 1, l.h, l.w, l.size, l.pad, l.stride, rearrangedimptr); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, weightptr, K, rearrangedimptr, N, 0.0f, outptr, N); partial_free_from_stack(N * K * sizeof(float)); } add_bias(l.output, l.biases, l.out_c, N); l.activation(l.output, l.outputs); #endif } void forward_convolutional_layer ( layer_struct l, network_struct net ) { #ifdef NNPACK struct nnp_size input_size = { l.w, l.h }; struct nnp_padding input_padding = { l.pad, l.pad, l.pad, l.pad }; struct nnp_size kernel_size = { l.size, l.size }; struct nnp_size stride = { l.stride, l.stride }; nnp_convolution_inference ( nnp_convolution_algorithm_implicit_gemm, nnp_convolution_transform_strategy_tuple_based, l.c, l.n, input_size, input_padding, kernel_size, stride, net.input, l.weights, l.biases, l.output, NULL, NULL, nnp_activation_relu, NULL, net.threadpool, NULL ); #else /* * --------------- * / / | * / / | * --------------- | * | | | * | | | * | in | | ____ * | | | | * | | / | * | |/ | im2col() * --------------- | * | * ////////////////////////////////////////////////// | * | * gemm() | * v * weight length (K) ------------------------------ * ------------------- | | * | | | | * num of filters (M) | | * | | * | | | | * ------------------- | | weight length (K) * | | * | | * | | * | | * ------------------------------ * output plane size (N) */ const int M = l.n; const int K = l.size * l.size * l.c; const int N = l.out_w * l.out_h; float *weightptr = l.weights; float *rearrangedimptr = (float*)alloc_from_stack(N * K * sizeof(float)); float *outptr = l.output; if (l.size == 1) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, weightptr, K, net.input, N, 0.0f, outptr, N); } else { im2col(net.input, l.c, l.h, l.w, l.size, l.pad, l.stride, rearrangedimptr); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, weightptr, K, rearrangedimptr, N, 0.0f, outptr, N); } add_bias(outptr, l.biases, l.out_c, N); l.activation(outptr, l.outputs); partial_free_from_stack(N * K * sizeof(float)); #endif } void forward_convolutional_layer_linear ( layer_struct l, network_struct net ) { #ifdef NNPACK struct nnp_size input_size = { l.w, l.h }; struct nnp_padding input_padding = { l.pad, l.pad, l.pad, l.pad }; struct nnp_size kernel_size = { l.size, l.size }; struct nnp_size stride = { l.stride, l.stride }; nnp_convolution_inference ( nnp_convolution_algorithm_implicit_gemm, nnp_convolution_transform_strategy_tuple_based, l.c, l.n, input_size, input_padding, kernel_size, stride, net.input, l.weights, l.biases, l.output, NULL, NULL, nnp_activation_identity, NULL, net.threadpool, NULL ); #else const int M = l.n; const int K = l.size * l.size * l.c; const int N = l.out_w * l.out_h; float *weightptr = l.weights; float *rearrangedimptr = (float*)alloc_from_stack(N * K * sizeof(float)); float *outptr = l.output; if (l.size == 1) { cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, weightptr, K, net.input, N, 0.0f, outptr, N); } else { im2col(net.input, l.c, l.h, l.w, l.size, l.pad, l.stride, rearrangedimptr); cblas_sgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans, M, N, K, 1.0f, weightptr, K, rearrangedimptr, N, 0.0f, outptr, N); } add_bias(outptr, l.biases, l.out_c, N); partial_free_from_stack(N * K * sizeof(float)); #endif } void forward_permute_layer ( layer_struct l, network_struct net ) { float *in = net.input; float *out = l.output; const int H = l.out_h; const int W = l.out_w; const int C = l.out_c; const int HW = H * W; int i = 0; int j = 0; for (i = 0; i < HW; ++i) { float *inptr = in + i; float *outptr = out + i * C; for (j = 0; j < C; ++j) { outptr[j] = inptr[j * HW]; } } } void forward_priorbox_layer ( layer_struct l, network_struct net ) { const int layer_width = l.w; const int layer_height = l.h; const int img_width = net.w; const int img_height = net.h; const float step_w = (float)(img_width) / layer_width; const float step_h = (float)(img_height) / layer_height; const float min_size = l.min_size; const float max_size = l.max_size; const float sqrt_min_max_size = sqrt(min_size * max_size); const float offset = 0.5f; const float aspect_ratios[4] = { sqrt(2.0f), sqrt(1.0f / 2.0f), sqrt(3.0f), sqrt(1.0f / 3.0f) }; const float variance[4] = {0.1f, 0.1f, 0.2f, 0.2f}; const int ar_num = l.aspect_ratio_num; const int num_priors = l.c; float *top_data = l.output; int idx = 0; int h = 0; int w = 0; int r = 0; int i = 0; int j = 0; for (h = 0; h < layer_height; ++h) { for (w = 0; w < layer_width; ++w) { float center_x = (w + offset) * step_w; float center_y = (h + offset) * step_h; float box_width = min_size; float box_height = min_size; top_data[idx++] = (center_x - box_width / 2.) / img_width; // xmin top_data[idx++] = (center_y - box_height / 2.) / img_height; // ymin top_data[idx++] = (center_x + box_width / 2.) / img_width; // xmax top_data[idx++] = (center_y + box_height / 2.) / img_height; // ymax if (max_size > 0.0f) { box_width = sqrt_min_max_size; box_height = sqrt_min_max_size; top_data[idx++] = (center_x - box_width / 2.) / img_width; // xmin top_data[idx++] = (center_y - box_height / 2.) / img_height; // ymin top_data[idx++] = (center_x + box_width / 2.) / img_width; // xmax top_data[idx++] = (center_y + box_height / 2.) / img_height; // ymax } // rest of prior for (r = 0; r < ar_num; ++r) { float ar = aspect_ratios[r]; box_width = min_size * ar; box_height = min_size / ar; top_data[idx++] = (center_x - box_width / 2.) / img_width; // xmin top_data[idx++] = (center_y - box_height / 2.) / img_height; // ymin top_data[idx++] = (center_x + box_width / 2.) / img_width; // xmax top_data[idx++] = (center_y + box_height / 2.) / img_height; // ymax } } } // set the variance for (h = 0; h < layer_height; ++h) { for (w = 0; w < layer_width; ++w) { for (i = 0; i < num_priors; ++i) { for (j = 0; j < 4; ++j) { top_data[idx++] = variance[j]; } } } } } float* preprocessed ( objdetect_struct* objdet_wksp ) { int netw = objdet_wksp->net.w; int neth = objdet_wksp->net.h; unsigned char* src = objdet_wksp->src; const float premean = 127.5f; const float prediv = 0.007843f; float *imbuf = (float *)alloc_from_stack(netw * neth * 3 * sizeof(float)); // split into whole b, whole g, whole r buffer, and normalize int idx = 0; int flatsize = netw * neth; float* imbufptr = imbuf; unsigned char* srcptr = src; // b for(idx = 0; idx < flatsize; ++idx) { imbufptr[idx] = ((*srcptr) - premean) * prediv; srcptr += 3; } // g imbufptr = imbuf + flatsize; srcptr = src + 1; for(idx = 0; idx < flatsize; ++idx) { imbufptr[idx] = ((*srcptr) - premean) * prediv; srcptr += 3; } // r imbufptr = imbuf + (flatsize << 1); srcptr = src + 2; for(idx = 0; idx < flatsize; ++idx) { imbufptr[idx] = ((*srcptr) - premean) * prediv; srcptr += 3; } return imbuf; } void network_predict ( network_struct net ) { // forward propagation int i = 0; for(i = 0; i < net.n; ++i) { layer_struct l = net.layers[i]; l.forward(l, net); net.input = l.output; } } int nms_comparator ( const void *pa, const void *pb ) { score_index_struct a = *(score_index_struct *)pa; score_index_struct b = *(score_index_struct *)pb; float diff = a.score - b.score; if(diff < 0) { return 1; } else if(diff > 0) { return -1; } return 0; } void get_detection_out ( objdetect_struct* objdet_wksp ) { network_struct net = objdet_wksp->net; float *mbox_conf_ptr = net.layers[84].output; const int num_classes = objdet_wksp->class_num + 1; // 1 for background const int num_conf = net.layers[84].outputs / num_classes; int i = 0; int j = 0; int k = 0; // softmax on mbox_conf for (i = 0; i < num_conf; ++i) { float maxconf = 0.0f; float sumconf = 0.0f; for (j = 0; j < num_classes; ++j) { if (mbox_conf_ptr[j] > maxconf) { maxconf = mbox_conf_ptr[j]; } } for (j = 0; j < num_classes; ++j) { mbox_conf_ptr[j] = exp(mbox_conf_ptr[j] - maxconf); sumconf += mbox_conf_ptr[j]; } for (j = 0; j < num_classes; ++j) { mbox_conf_ptr[j] /= sumconf; } mbox_conf_ptr += num_classes; } const float* loc_data = net.layers[83].output; const float* conf_data = net.layers[84].output; const float* prior_data = net.layers[85].output; const int num_priors = (net.layers[85].outputs >> 3); // get bbox candidates, note x, y here are center x, y box_struct *decode_bboxes = (box_struct *)alloc_from_stack(num_priors * sizeof(box_struct)); for (i = 0; i < num_priors; ++i) { int start_idx = i * 4; const float prior_bbox_xmin = prior_data[start_idx]; const float prior_bbox_ymin = prior_data[start_idx + 1]; const float prior_bbox_xmax = prior_data[start_idx + 2]; const float prior_bbox_ymax = prior_data[start_idx + 3]; const float prior_width = prior_bbox_xmax - prior_bbox_xmin; const float prior_height = prior_bbox_ymax - prior_bbox_ymin; const float prior_center_x = (prior_bbox_xmin + prior_bbox_xmax) / 2.0f; const float prior_center_y = (prior_bbox_ymin + prior_bbox_ymax) / 2.0f; const float bbox_xmin = loc_data[start_idx]; const float bbox_ymin = loc_data[start_idx + 1]; const float bbox_xmax = loc_data[start_idx + 2]; const float bbox_ymax = loc_data[start_idx + 3]; const int shift_to_var = 4 * num_priors; decode_bboxes[i].x = prior_data[shift_to_var + start_idx] * bbox_xmin * prior_width + prior_center_x; decode_bboxes[i].y = prior_data[shift_to_var + start_idx + 1] * bbox_ymin * prior_height + prior_center_y; decode_bboxes[i].w = exp(prior_data[shift_to_var + start_idx + 2] * bbox_xmax) * prior_width; decode_bboxes[i].h = exp(prior_data[shift_to_var + start_idx + 3] * bbox_ymax) * prior_height; } // do nms const float score_threshold = objdet_wksp->thresh; const float nms_threshold = objdet_wksp->nms_thresh; //const float score_threshold = 0.35f; //const float nms_threshold = 0.75f; const int topk = 100; int num_resobj = 0; const int imw = objdet_wksp->srcw; const int imh = objdet_wksp->srch; int num_rest = 0; score_index_struct *score_index_vec = (score_index_struct *)alloc_from_stack(num_priors * sizeof(score_index_struct)); const float *scores = conf_data + 1; // person for (j = 0; j < num_priors; ++j) { if (*scores > score_threshold) { score_index_vec[num_rest].index = j; score_index_vec[num_rest].score = *scores; ++num_rest; } scores += num_classes; } qsort(score_index_vec, num_rest, sizeof(score_index_struct), nms_comparator); int veclength = num_rest > topk ? topk : num_rest; //nms for(j = 0; j < veclength; ++j) { if(score_index_vec[j].index == -1) { continue; } box_struct a = decode_bboxes[score_index_vec[j].index]; for(k = j + 1; k < veclength; ++k) { box_struct b = decode_bboxes[score_index_vec[k].index]; float overlap = box_iou(a, b); if(overlap > nms_threshold) { score_index_vec[k].index = -1; } } } //fill in and resize back to result for(j = 0; j < veclength; ++j) { if(score_index_vec[j].index == -1) { continue; } const float score = score_index_vec[j].score; //printf("prob: %f\n", score); box_struct a = decode_bboxes[score_index_vec[j].index]; const int width = a.w * imw; const int height = a.h * imh; const int xmin = a.x * imw - (width >> 1); const int ymin = a.y * imh - (height >> 1); objdet_wksp->output[5 * num_resobj + 1] = xmin; objdet_wksp->output[5 * num_resobj + 2] = ymin; objdet_wksp->output[5 * num_resobj + 3] = width; objdet_wksp->output[5 * num_resobj + 4] = height; objdet_wksp->output[5 * num_resobj + 5] = (int)(100 * score); ++num_resobj; } partial_free_from_stack(num_priors * sizeof(score_index_struct)); objdet_wksp->output[0] = num_resobj; partial_free_from_stack(num_priors * sizeof(box_struct)); } void clear_network ( network_struct net ) { int i = 0; for(i = 0; i < net.n; ++i) { layer_struct l = net.layers[i]; memset(l.output, 0, l.outputs * sizeof(float)); } }
GB_unaryop__identity_int64_int64.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__identity_int64_int64 // op(A') function: GB_tran__identity_int64_int64 // C type: int64_t // A type: int64_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ int64_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_CASTING(z, x) \ int64_t z = (int64_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_IDENTITY || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int64_int64 ( int64_t *restrict Cx, const int64_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__identity_int64_int64 ( 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
GB_binop__plus_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_01__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_02__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_03__plus_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__plus_fp32) // A*D function (colscale): GB (_AxD__plus_fp32) // D*A function (rowscale): GB (_DxB__plus_fp32) // C+=B function (dense accum): GB (_Cdense_accumB__plus_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__plus_fp32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__plus_fp32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__plus_fp32) // C=scalar+B GB (_bind1st__plus_fp32) // C=scalar+B' GB (_bind1st_tran__plus_fp32) // C=A+scalar GB (_bind2nd__plus_fp32) // C=A'+scalar GB (_bind2nd_tran__plus_fp32) // C type: float // A type: float // B,b type: float // BinaryOp: cij = (aij + bij) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ float aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ float bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x + y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_PLUS || GxB_NO_FP32 || GxB_NO_PLUS_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__plus_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__plus_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__plus_fp32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__plus_fp32) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type float float bwork = (*((float *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__plus_fp32) ( 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 float *restrict Cx = (float *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__plus_fp32) ( 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 float *restrict Cx = (float *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__plus_fp32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__plus_fp32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__plus_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__plus_fp32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__plus_fp32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__plus_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; float bij = GBX (Bx, p, false) ; Cx [p] = (x + bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__plus_fp32) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; float aij = GBX (Ax, p, false) ; Cx [p] = (aij + y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x + aij) ; \ } GrB_Info GB (_bind1st_tran__plus_fp32) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij + y) ; \ } GrB_Info GB (_bind2nd_tran__plus_fp32) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
HybridRepSetReader.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2019 QMCPACK developers. // // File developed by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory // // File created by: Ye Luo, yeluo@anl.gov, Argonne National Laboratory ////////////////////////////////////////////////////////////////////////////////////// /** @file * * derived from SplineSetReader */ #ifndef QMCPLUSPLUS_HYBRIDREP_READER_H #define QMCPLUSPLUS_HYBRIDREP_READER_H #include "Numerics/Quadrature.h" #include "Numerics/Bessel.h" #include "QMCWaveFunctions/BsplineFactory/HybridRepCenterOrbitals.h" #include "OhmmsData/AttributeSet.h" #include "config/stdlib/math.hpp" //#include "QMCHamiltonians/Ylm.h" //#define PRINT_RADIAL namespace qmcplusplus { template<typename ST, typename LT> struct Gvectors { typedef TinyVector<ST, 3> PosType; typedef std::complex<ST> ValueType; const LT& Lattice; std::vector<PosType> gvecs_cart; //Cartesian. std::vector<ST> gmag; const size_t NumGvecs; Gvectors(const std::vector<TinyVector<int, 3>>& gvecs_in, const LT& Lattice_in, const TinyVector<int, 3>& HalfG, size_t first, size_t last) : Lattice(Lattice_in), NumGvecs(last - first) { gvecs_cart.resize(NumGvecs); gmag.resize(NumGvecs); #pragma omp parallel for for (size_t ig = 0; ig < NumGvecs; ig++) { TinyVector<ST, 3> gvec_shift; gvec_shift = gvecs_in[ig + first] + HalfG * 0.5; gvecs_cart[ig] = Lattice.k_cart(gvec_shift); gmag[ig] = std::sqrt(dot(gvecs_cart[ig], gvecs_cart[ig])); } } template<typename YLM_ENGINE, typename VVT> void calc_Ylm_G(const size_t ig, YLM_ENGINE& Ylm, VVT& YlmG) const { PosType Ghat(0.0, 0.0, 1.0); if (gmag[ig] > 0) Ghat = gvecs_cart[ig] / gmag[ig]; Ylm.evaluateV(Ghat[0], Ghat[1], Ghat[2], YlmG.data()); } template<typename VVT> inline void calc_jlm_G(const int lmax, ST& r, const size_t ig, VVT& j_lm_G) const { bessel_steed_array_cpu(lmax, gmag[ig] * r, j_lm_G.data()); for (size_t l = lmax; l > 0; l--) for (size_t lm = l * l; lm < (l + 1) * (l + 1); lm++) j_lm_G[lm] = j_lm_G[l]; } template<typename PT, typename VT> inline void calc_phase_shift(const PT& RSoA, const size_t ig, VT& phase_shift_real, VT& phase_shift_imag) const { const ST* restrict px = RSoA.data(0); const ST* restrict py = RSoA.data(1); const ST* restrict pz = RSoA.data(2); ST* restrict v_r = phase_shift_real.data(); ST* restrict v_i = phase_shift_imag.data(); const ST& gv_x = gvecs_cart[ig][0]; const ST& gv_y = gvecs_cart[ig][1]; const ST& gv_z = gvecs_cart[ig][2]; #pragma omp simd aligned(px, py, pz, v_r, v_i: QMC_SIMD_ALIGNMENT) for (size_t iat = 0; iat < RSoA.size(); iat++) qmcplusplus::sincos(px[iat] * gv_x + py[iat] * gv_y + pz[iat] * gv_z, v_i + iat, v_r + iat); } template<typename PT> ValueType evaluate_psi_r(const Vector<std::complex<double>>& cG, const PT& pos) { assert(cG.size() == NumGvecs); std::complex<ST> val(0.0, 0.0); for (size_t ig = 0; ig < NumGvecs; ig++) { ST s, c; qmcplusplus::sincos(dot(gvecs_cart[ig], pos), &s, &c); ValueType pw0(c, s); val += cG[ig] * pw0; } return val; } template<typename PT> void evaluate_psi_r(const Vector<std::complex<double>>& cG, const PT& pos, ValueType& phi, ValueType& d2phi) { assert(cG.size() == NumGvecs); d2phi = phi = 0.0; for (size_t ig = 0; ig < NumGvecs; ig++) { ST s, c; qmcplusplus::sincos(dot(gvecs_cart[ig], pos), &s, &c); ValueType pw0(c, s); phi += cG[ig] * pw0; d2phi += cG[ig] * pw0 * (-dot(gvecs_cart[ig], gvecs_cart[ig])); } } double evaluate_KE(const Vector<std::complex<double>>& cG) { assert(cG.size() == NumGvecs); double KE = 0; for (size_t ig = 0; ig < NumGvecs; ig++) KE += dot(gvecs_cart[ig], gvecs_cart[ig]) * (cG[ig].real() * cG[ig].real() + cG[ig].imag() * cG[ig].imag()); return KE / 2.0; } }; /** General HybridRepSetReader to handle any unitcell */ template<typename SA> struct HybridRepSetReader : public SplineSetReader<SA> { typedef SplineSetReader<SA> BaseReader; using BaseReader::bspline; using BaseReader::mybuilder; using BaseReader::rotate_phase_i; using BaseReader::rotate_phase_r; using typename BaseReader::DataType; HybridRepSetReader(EinsplineSetBuilder* e) : BaseReader(e) {} /** initialize basic parameters of atomic orbitals */ void initialize_hybridrep_atomic_centers() override { OhmmsAttributeSet a; std::string scheme_name("Consistent"); std::string s_function_name("LEKS2018"); a.add(scheme_name, "smoothing_scheme"); a.add(s_function_name, "smoothing_function"); a.put(mybuilder->XMLRoot); // assign smooth_scheme if (scheme_name == "Consistent") bspline->smooth_scheme = SA::smoothing_schemes::CONSISTENT; else if (scheme_name == "SmoothAll") bspline->smooth_scheme = SA::smoothing_schemes::SMOOTHALL; else if (scheme_name == "SmoothPartial") bspline->smooth_scheme = SA::smoothing_schemes::SMOOTHPARTIAL; else APP_ABORT("initialize_hybridrep_atomic_centers wrong smoothing_scheme name! Only allows Consistent, SmoothAll or " "SmoothPartial."); // assign smooth_function if (s_function_name == "LEKS2018") bspline->smooth_func_id = smoothing_functions::LEKS2018; else if (s_function_name == "coscos") bspline->smooth_func_id = smoothing_functions::COSCOS; else if (s_function_name == "linear") bspline->smooth_func_id = smoothing_functions::LINEAR; else APP_ABORT( "initialize_hybridrep_atomic_centers wrong smoothing_function name! Only allows LEKS2018, coscos or linear."); app_log() << "Hybrid orbital representation uses " << scheme_name << " smoothing scheme and " << s_function_name << " smoothing function." << std::endl; bspline->set_info(*(mybuilder->SourcePtcl), mybuilder->TargetPtcl, mybuilder->Super2Prim); auto& centers = bspline->AtomicCenters; auto& ACInfo = mybuilder->AtomicCentersInfo; // load atomic center info only when it is not initialized if (centers.size() == 0) { bool success = true; app_log() << "Reading atomic center info for hybrid representation" << std::endl; for (int center_idx = 0; center_idx < ACInfo.Ncenters; center_idx++) { const int my_GroupID = ACInfo.GroupID[center_idx]; if (ACInfo.cutoff[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'cutoff_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.inner_cutoff[center_idx] < 0) { const double inner_cutoff = std::max(ACInfo.cutoff[center_idx] - 0.3, 0.0); app_log() << "Hybrid orbital representation setting 'inner_cutoff' to " << inner_cutoff << " for group " << my_GroupID << " as atom " << center_idx << std::endl; // overwrite the inner_cutoff of all the atoms of the same species for (int id = 0; id < ACInfo.Ncenters; id++) if (my_GroupID == ACInfo.GroupID[id]) ACInfo.inner_cutoff[id] = inner_cutoff; } else if (ACInfo.inner_cutoff[center_idx] > ACInfo.cutoff[center_idx]) { app_error() << "Hybrid orbital representation 'inner_cutoff' must be smaller than 'spline_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.cutoff[center_idx] > 0) { if (ACInfo.lmax[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'lmax' for atom " << center_idx << std::endl; success = false; } if (ACInfo.spline_radius[center_idx] < 0 && ACInfo.spline_npoints[center_idx] < 0) { app_log() << "Parameters 'spline_radius' and 'spline_npoints' for group " << my_GroupID << " as atom " << center_idx << " are not specified." << std::endl; const double delta = std::min(0.02, ACInfo.cutoff[center_idx] / 4.0); const int n_grid_point = std::ceil((ACInfo.cutoff[center_idx] + 1e-4) / delta) + 3; for (int id = 0; id < ACInfo.Ncenters; id++) if (my_GroupID == ACInfo.GroupID[id]) { ACInfo.spline_npoints[id] = n_grid_point; ACInfo.spline_radius[id] = (n_grid_point - 1) * delta; } app_log() << " Based on default grid point distance " << delta << std::endl; app_log() << " Setting 'spline_npoints' to " << ACInfo.spline_npoints[center_idx] << std::endl; app_log() << " Setting 'spline_radius' to " << ACInfo.spline_radius[center_idx] << std::endl; } else { if (ACInfo.spline_radius[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'spline_radius' for atom " << center_idx << std::endl; success = false; } if (ACInfo.spline_npoints[center_idx] < 0) { app_error() << "Hybrid orbital representation needs parameter 'spline_npoints' for atom " << center_idx << std::endl; success = false; } } // check maximally allowed cutoff_radius double max_allowed_cutoff = ACInfo.spline_radius[center_idx] - 2.0 * ACInfo.spline_radius[center_idx] / (ACInfo.spline_npoints[center_idx] - 1); if (success && ACInfo.cutoff[center_idx] > max_allowed_cutoff) { app_error() << "Hybrid orbital representation requires cutoff_radius<=" << max_allowed_cutoff << " calculated by spline_radius-2*spline_radius/(spline_npoints-1) for atom " << center_idx << std::endl; success = false; } } else { // no atomic regions for this atom type ACInfo.spline_radius[center_idx] = 0.0; ACInfo.spline_npoints[center_idx] = 0; ACInfo.lmax[center_idx] = 0; } } if (!success) BaseReader::myComm->barrier_and_abort("initialize_hybridrep_atomic_centers Failed to initialize atomic centers " "in hybrid orbital representation!"); for (int center_idx = 0; center_idx < ACInfo.Ncenters; center_idx++) { AtomicOrbitals<DataType> oneCenter(ACInfo.lmax[center_idx]); oneCenter.set_info(ACInfo.ion_pos[center_idx], ACInfo.cutoff[center_idx], ACInfo.inner_cutoff[center_idx], ACInfo.spline_radius[center_idx], ACInfo.non_overlapping_radius[center_idx], ACInfo.spline_npoints[center_idx]); centers.push_back(oneCenter); } } } /** initialize construct atomic orbital radial functions from plane waves */ inline void create_atomic_centers_Gspace(Vector<std::complex<double>>& cG, Communicate& band_group_comm, int iorb) override { band_group_comm.bcast(rotate_phase_r); band_group_comm.bcast(rotate_phase_i); band_group_comm.bcast(cG); //distribute G-vectors over processor groups const int Ngvecs = mybuilder->Gvecs[0].size(); const int Nprocs = band_group_comm.size(); const int Ngvecgroups = std::min(Ngvecs, Nprocs); Communicate gvec_group_comm(band_group_comm, Ngvecgroups); std::vector<int> gvec_groups(Ngvecgroups + 1, 0); FairDivideLow(Ngvecs, Ngvecgroups, gvec_groups); const int gvec_first = gvec_groups[gvec_group_comm.getGroupID()]; const int gvec_last = gvec_groups[gvec_group_comm.getGroupID() + 1]; // prepare Gvecs Ylm(G) typedef typename EinsplineSetBuilder::UnitCellType UnitCellType; Gvectors<double, UnitCellType> Gvecs(mybuilder->Gvecs[0], mybuilder->PrimCell, bspline->HalfG, gvec_first, gvec_last); // if(band_group_comm.isGroupLeader()) std::cout << "print band=" << iorb << " KE=" << Gvecs.evaluate_KE(cG) << std::endl; std::vector<AtomicOrbitals<DataType>>& centers = bspline->AtomicCenters; app_log() << "Transforming band " << iorb << " on Rank 0" << std::endl; // collect atomic centers by group std::vector<int> uniq_species; for (int center_idx = 0; center_idx < centers.size(); center_idx++) { auto& ACInfo = mybuilder->AtomicCentersInfo; const int my_GroupID = ACInfo.GroupID[center_idx]; int found_idx = -1; for (size_t idx = 0; idx < uniq_species.size(); idx++) if (my_GroupID == uniq_species[idx]) { found_idx = idx; break; } if (found_idx < 0) uniq_species.push_back(my_GroupID); } // construct group list std::vector<std::vector<int>> group_list(uniq_species.size()); for (int center_idx = 0; center_idx < centers.size(); center_idx++) { auto& ACInfo = mybuilder->AtomicCentersInfo; const int my_GroupID = ACInfo.GroupID[center_idx]; for (size_t idx = 0; idx < uniq_species.size(); idx++) if (my_GroupID == uniq_species[idx]) { group_list[idx].push_back(center_idx); break; } } for (int group_idx = 0; group_idx < group_list.size(); group_idx++) { const auto& mygroup = group_list[group_idx]; const double spline_radius = centers[mygroup[0]].getSplineRadius(); const int spline_npoints = centers[mygroup[0]].getSplineNpoints(); const int lmax = centers[mygroup[0]].getLmax(); const double delta = spline_radius / static_cast<double>(spline_npoints - 1); const int lm_tot = (lmax + 1) * (lmax + 1); const size_t natoms = mygroup.size(); const int policy = lm_tot > natoms ? 0 : 1; std::vector<std::complex<double>> i_power(lm_tot); // rotate phase is introduced here. std::complex<double> i_temp(rotate_phase_r, rotate_phase_i); for (size_t l = 0; l <= lmax; l++) { for (size_t lm = l * l; lm < (l + 1) * (l + 1); lm++) i_power[lm] = i_temp; i_temp *= std::complex<double>(0.0, 1.0); } std::vector<Matrix<double>> all_vals(natoms); std::vector<std::vector<aligned_vector<double>>> vals_local(spline_npoints * omp_get_max_threads()); VectorSoaContainer<double, 3> myRSoA(natoms); for (size_t idx = 0; idx < natoms; idx++) { all_vals[idx].resize(spline_npoints, lm_tot * 2); all_vals[idx] = 0.0; myRSoA(idx) = centers[mygroup[idx]].getCenterPos(); } #pragma omp parallel { const size_t tid = omp_get_thread_num(); const size_t nt = omp_get_num_threads(); for (int ip = 0; ip < spline_npoints; ip++) { const size_t ip_idx = tid * spline_npoints + ip; if (policy == 1) { vals_local[ip_idx].resize(lm_tot * 2); for (size_t lm = 0; lm < lm_tot * 2; lm++) { auto& vals = vals_local[ip_idx][lm]; vals.resize(natoms); std::fill(vals.begin(), vals.end(), 0.0); } } else { vals_local[ip_idx].resize(natoms * 2); for (size_t iat = 0; iat < natoms * 2; iat++) { auto& vals = vals_local[ip_idx][iat]; vals.resize(lm_tot); std::fill(vals.begin(), vals.end(), 0.0); } } } const size_t size_pw_tile = 32; const size_t num_pw_tiles = (Gvecs.NumGvecs + size_pw_tile - 1) / size_pw_tile; aligned_vector<double> j_lm_G(lm_tot, 0.0); std::vector<aligned_vector<double>> phase_shift_r(size_pw_tile); std::vector<aligned_vector<double>> phase_shift_i(size_pw_tile); std::vector<aligned_vector<double>> YlmG(size_pw_tile); for (size_t ig = 0; ig < size_pw_tile; ig++) { phase_shift_r[ig].resize(natoms); phase_shift_i[ig].resize(natoms); YlmG[ig].resize(lm_tot); } SoaSphericalTensor<double> Ylm(lmax); #pragma omp for for (size_t tile_id = 0; tile_id < num_pw_tiles; tile_id++) { const size_t ig_first = tile_id * size_pw_tile; const size_t ig_last = std::min((tile_id + 1) * size_pw_tile, Gvecs.NumGvecs); for (size_t ig = ig_first; ig < ig_last; ig++) { const size_t ig_local = ig - ig_first; // calculate phase shift for all the centers of this group Gvecs.calc_phase_shift(myRSoA, ig, phase_shift_r[ig_local], phase_shift_i[ig_local]); Gvecs.calc_Ylm_G(ig, Ylm, YlmG[ig_local]); } for (int ip = 0; ip < spline_npoints; ip++) { double r = delta * static_cast<double>(ip); const size_t ip_idx = tid * spline_npoints + ip; for (size_t ig = ig_first; ig < ig_last; ig++) { const size_t ig_local = ig - ig_first; // calculate spherical bessel function Gvecs.calc_jlm_G(lmax, r, ig, j_lm_G); for (size_t lm = 0; lm < lm_tot; lm++) j_lm_G[lm] *= YlmG[ig_local][lm]; const double cG_r = cG[ig + gvec_first].real(); const double cG_i = cG[ig + gvec_first].imag(); if (policy == 1) { for (size_t lm = 0; lm < lm_tot; lm++) { double* restrict vals_r = vals_local[ip_idx][lm * 2].data(); double* restrict vals_i = vals_local[ip_idx][lm * 2 + 1].data(); const double* restrict ps_r_ptr = phase_shift_r[ig_local].data(); const double* restrict ps_i_ptr = phase_shift_i[ig_local].data(); double cG_j_r = cG_r * j_lm_G[lm]; double cG_j_i = cG_i * j_lm_G[lm]; #pragma omp simd aligned(vals_r, vals_i, ps_r_ptr, ps_i_ptr: QMC_SIMD_ALIGNMENT) for (size_t idx = 0; idx < natoms; idx++) { const double ps_r = ps_r_ptr[idx]; const double ps_i = ps_i_ptr[idx]; vals_r[idx] += cG_j_r * ps_r - cG_j_i * ps_i; vals_i[idx] += cG_j_i * ps_r + cG_j_r * ps_i; } } } else { for (size_t idx = 0; idx < natoms; idx++) { double* restrict vals_r = vals_local[ip_idx][idx * 2].data(); double* restrict vals_i = vals_local[ip_idx][idx * 2 + 1].data(); const double* restrict j_lm_G_ptr = j_lm_G.data(); double cG_ps_r = cG_r * phase_shift_r[ig_local][idx] - cG_i * phase_shift_i[ig_local][idx]; double cG_ps_i = cG_i * phase_shift_r[ig_local][idx] + cG_r * phase_shift_i[ig_local][idx]; #pragma omp simd aligned(vals_r, vals_i, j_lm_G_ptr: QMC_SIMD_ALIGNMENT) for (size_t lm = 0; lm < lm_tot; lm++) { const double jlm = j_lm_G_ptr[lm]; vals_r[lm] += cG_ps_r * jlm; vals_i[lm] += cG_ps_i * jlm; } } } } } } #pragma omp for collapse(2) for (int ip = 0; ip < spline_npoints; ip++) for (size_t idx = 0; idx < natoms; idx++) { double* vals = all_vals[idx][ip]; for (size_t tid = 0; tid < nt; tid++) for (size_t lm = 0; lm < lm_tot; lm++) { double vals_th_r, vals_th_i; const size_t ip_idx = tid * spline_npoints + ip; if (policy == 1) { vals_th_r = vals_local[ip_idx][lm * 2][idx]; vals_th_i = vals_local[ip_idx][lm * 2 + 1][idx]; } else { vals_th_r = vals_local[ip_idx][idx * 2][lm]; vals_th_i = vals_local[ip_idx][idx * 2 + 1][lm]; } const double real_tmp = 4.0 * M_PI * i_power[lm].real(); const double imag_tmp = 4.0 * M_PI * i_power[lm].imag(); vals[lm] += vals_th_r * real_tmp - vals_th_i * imag_tmp; vals[lm + lm_tot] += vals_th_i * real_tmp + vals_th_r * imag_tmp; } } } //app_log() << "Building band " << iorb << " at center " << center_idx << std::endl; for (size_t idx = 0; idx < natoms; idx++) { // reduce all_vals band_group_comm.reduce_in_place(all_vals[idx].data(), all_vals[idx].size()); if (!band_group_comm.isGroupLeader()) continue; #pragma omp parallel for for (int lm = 0; lm < lm_tot; lm++) { auto& mycenter = centers[mygroup[idx]]; aligned_vector<double> splineData_r(spline_npoints); UBspline_1d_d* atomic_spline_r; for (size_t ip = 0; ip < spline_npoints; ip++) splineData_r[ip] = all_vals[idx][ip][lm]; atomic_spline_r = einspline::create(atomic_spline_r, 0.0, spline_radius, spline_npoints, splineData_r.data(), ((lm == 0) || (lm > 3))); if (!bspline->is_complex) { mycenter.set_spline(atomic_spline_r, lm, iorb); einspline::destroy(atomic_spline_r); } else { aligned_vector<double> splineData_i(spline_npoints); UBspline_1d_d* atomic_spline_i; for (size_t ip = 0; ip < spline_npoints; ip++) splineData_i[ip] = all_vals[idx][ip][lm + lm_tot]; atomic_spline_i = einspline::create(atomic_spline_i, 0.0, spline_radius, spline_npoints, splineData_i.data(), ((lm == 0) || (lm > 3))); mycenter.set_spline(atomic_spline_r, lm, iorb * 2); mycenter.set_spline(atomic_spline_i, lm, iorb * 2 + 1); einspline::destroy(atomic_spline_r); einspline::destroy(atomic_spline_i); } } } #ifdef PRINT_RADIAL char fname[64]; sprintf(fname, "band_%d_center_%d_pw.dat", iorb, center_idx); FILE* fout_pw = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_v.dat", iorb, center_idx); FILE* fout_spline_v = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_g.dat", iorb, center_idx); FILE* fout_spline_g = fopen(fname, "w"); sprintf(fname, "band_%d_center_%d_spline_l.dat", iorb, center_idx); FILE* fout_spline_l = fopen(fname, "w"); fprintf(fout_pw, "# r vals(lm)\n"); fprintf(fout_spline_v, "# r vals(lm)\n"); fprintf(fout_spline_g, "# r grads(lm)\n"); fprintf(fout_spline_l, "# r lapls(lm)\n"); // write to file for plotting for (int ip = 0; ip < spline_npoints - 1; ip++) { double r = delta * static_cast<double>(ip); mycenter.SplineInst->evaluate_vgl(r, mycenter.localV, mycenter.localG, mycenter.localL); fprintf(fout_pw, "%15.10lf ", r); fprintf(fout_spline_v, "%15.10lf ", r); fprintf(fout_spline_g, "%15.10lf ", r); fprintf(fout_spline_l, "%15.10lf ", r); for (int lm = 0; lm < lm_tot; lm++) { fprintf(fout_pw, "%15.10lf %15.10lf ", all_vals[center_idx][ip][lm].real(), all_vals[center_idx][ip][lm].imag()); fprintf(fout_spline_v, "%15.10lf %15.10lf ", mycenter.localV[lm * mycenter.Npad + iorb * 2], mycenter.localV[lm * mycenter.Npad + iorb * 2 + 1]); fprintf(fout_spline_g, "%15.10lf %15.10lf ", mycenter.localG[lm * mycenter.Npad + iorb * 2], mycenter.localG[lm * mycenter.Npad + iorb * 2 + 1]); fprintf(fout_spline_l, "%15.10lf %15.10lf ", mycenter.localL[lm * mycenter.Npad + iorb * 2], mycenter.localL[lm * mycenter.Npad + iorb * 2 + 1]); } fprintf(fout_pw, "\n"); fprintf(fout_spline_v, "\n"); fprintf(fout_spline_g, "\n"); fprintf(fout_spline_l, "\n"); } fclose(fout_pw); fclose(fout_spline_v); fclose(fout_spline_g); fclose(fout_spline_l); #endif } } }; } // namespace qmcplusplus #endif
GB_binop__isle_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__isle_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_uint64) // A*D function (colscale): GB (_AxD__isle_uint64) // D*A function (rowscale): GB (_DxB__isle_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__isle_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__isle_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_uint64) // C=scalar+B GB (_bind1st__isle_uint64) // C=scalar+B' GB (_bind1st_tran__isle_uint64) // C=A+scalar GB (_bind2nd__isle_uint64) // C=A'+scalar GB (_bind2nd_tran__isle_uint64) // C type: uint64_t // A type: uint64_t // A pattern? 0 // B type: uint64_t // B pattern? 0 // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_ISLE || GxB_NO_UINT64 || GxB_NO_ISLE_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__isle_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__isle_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isle_uint64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isle_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint64_t alpha_scalar ; uint64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint64_t *) alpha_scalar_in)) ; beta_scalar = (*((uint64_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isle_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__isle_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__isle_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__isle_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__isle_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x <= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isle_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__isle_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB (_bind2nd_tran__isle_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
dz1z2.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> void Usage(char *prog_name); #define ACCURACY 0.01 /* * worksharing */ double sequential_solution(int argc, char *argv[]) { long long n, i; double factor; double sum = 0.0; if (argc != 2) Usage(argv[0]); n = strtoll(argv[1], NULL, 10); if (n < 1) Usage(argv[0]); 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)); return sum; } double parallel_solution(int argc, char *argv[]) { long long n, i; double factor; double sum = 0.0; if (argc != 2) Usage(argv[0]); n = strtoll(argv[1], NULL, 10); if (n < 1) Usage(argv[0]); printf("Before for loop, factor = %f.\n", factor); #pragma omp parallel for reduction(+:sum) lastprivate(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)); return sum; } int main(int argc, char *argv[]) { printf("---------------------Sequential execution---------------------\n"); double start_time_seq = omp_get_wtime(); double sum_seq = sequential_solution(argc, argv); double end_time_seq = omp_get_wtime(); printf("----------------------Parallel execution----------------------\n"); double start_time_parallel = omp_get_wtime(); double sum_parallel = parallel_solution(argc, argv); double end_time_parallel = omp_get_wtime(); printf("\nSequential elapsed time: %lfs\n", end_time_seq - start_time_seq); printf("Parallel elapsed time: %lfs\n", end_time_parallel - start_time_parallel); if (fabs(sum_seq - sum_parallel) < ACCURACY) printf("Test PASSED\n"); else printf("Test FAILED\n"); 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); }
GB_binop__band_uint64.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__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_01__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__band_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__band_uint64) // A*D function (colscale): GB (_AxD__band_uint64) // D*A function (rowscale): GB (_DxB__band_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__band_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__band_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__band_uint64) // C=scalar+B GB (_bind1st__band_uint64) // C=scalar+B' GB (_bind1st_tran__band_uint64) // C=A+scalar GB (_bind2nd__band_uint64) // C=A'+scalar GB (_bind2nd_tran__band_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij) & (bij) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (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_BAND || GxB_NO_UINT64 || GxB_NO_BAND_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__band_uint64) ( 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__band_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__band_uint64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint64_t uint64_t bwork = (*((uint64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__band_uint64) ( 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 uint64_t *restrict Cx = (uint64_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__band_uint64) ( 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 uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__band_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__band_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__band_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__band_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_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__band_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__band_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = (x) & (bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__band_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = (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) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x) & (aij) ; \ } GrB_Info GB (_bind1st_tran__band_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij) & (y) ; \ } GrB_Info GB (_bind2nd_tran__band_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
core_math.h
// == mojo ==================================================================== // // Copyright (c) gnawice@gnawice.com. All rights reserved. // See LICENSE in root folder // // 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. // // ============================================================================ // core_math.h: defines matrix class and math functions // ==================================================================== mojo == #pragma once #include <math.h> #include <string.h> #include <string> #include <cstdlib> #include <random> #include <algorithm> #include <immintrin.h> namespace mojo { enum pad_type { zero = 0, edge = 1, median_edge = 2 }; inline float dot(const float *x1, const float *x2, const int size) { switch (size) { case 1: return x1[0] * x2[0]; case 2: return x1[0] * x2[0] + x1[1] * x2[1]; case 3: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2]; case 4: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3]; case 5: return x1[0] * x2[0] + x1[1] * x2[1] + x1[2] * x2[2] + x1[3] * x2[3] + x1[4] * x2[4]; default: float v = 0; for (int i = 0; i<size; i++) v += x1[i] * x2[i]; return v; }; } inline float unwrap_2d_dot(const float *x1, const float *x2, const int size, int stride1, int stride2) { float v=0; for(int j=0; j<size; j++) v+= dot(&x1[stride1*j],&x2[stride2*j],size); return v; } // second item is rotated 180 (this is a convolution) inline float dot_rot180(const float *x1, const float *x2, const int size) { switch(size) { case 1: return x1[0]*x2[0]; case 2: return x1[0]*x2[1]+x1[1]*x2[0]; case 3: return x1[0]*x2[2]+x1[1]*x2[1]+x1[2]*x2[0]; case 4: return x1[0]*x2[3]+x1[1]*x2[2]+x1[2]*x2[1]+x1[3]*x2[0]; case 5: return x1[0]*x2[4]+x1[1]*x2[3]+x1[2]*x2[2]+x1[3]*x2[1]+x1[4]*x2[0]; default: float v=0; for(int i=0; i<size; i++) v+=x1[i]*x2[size-i-1]; return v; }; } inline float unwrap_2d_dot_rot180(const float *x1, const float *x2, const int size, int stride1, int stride2) { float v=0; for(int j=0; j<size; j++) { v+= dot_rot180(&x1[stride1*j],&x2[stride2*(size-j-1)],size); } return v; } inline void unwrap_aligned_NxN(const int N, float *aligned_out, const float *in, const int in_size, const int stride = 1) { const int node_size = (in_size - N)/stride + 1; int c1 = 0; int off = 0; const int inc_off = N*N*8; for (int j = 0; j < node_size; j += 1) // intput h { for (int i = 0; i < node_size; i += 1) // intput w { const float *tn = in + j*in_size + i; if(N==5) { for (int k = 0; k < 5; k++) { aligned_out[c1 + 0 + k * 40 + off] = tn[0 + 0 + in_size*k]; aligned_out[c1 + 8 + k * 40 + off] = tn[0 + 1 + in_size*k]; aligned_out[c1 + 16 + k * 40 + off] = tn[0 + 2 + in_size*k]; aligned_out[c1 + 24 + k * 40 + off] = tn[0 + 3 + in_size*k]; aligned_out[c1 + 32 + k * 40 + off] = tn[0 + 4 + in_size*k]; } } else if(N==3) { aligned_out[c1 + off] = tn[0]; aligned_out[c1 + 8 + off] = tn[0 + 1]; aligned_out[c1 + 16 + off] = tn[0 + 2]; aligned_out[c1 + 24 + off] = tn[0 + in_size]; aligned_out[c1 + 32 + off] = tn[0 + 1 + in_size]; aligned_out[c1 + 40 + off] = tn[0 + 2 + in_size]; aligned_out[c1 + 48 + off] = tn[0 + 2 * in_size]; aligned_out[c1 + 56 + off] = tn[0 + 1 + 2 * in_size]; aligned_out[c1 + 64 + off] = tn[0 + 2 + 2 * in_size]; } else { int cnt=0; for (int k = 0; k < N; k++) { for (int m = 0; m < N; m++) { aligned_out[c1 + cnt*8 + off] = tn[0 + m + in_size*k]; cnt++; } } } off++; if (off > 7) { off = 0; c1 += inc_off; } } } } inline void dotsum_unwrapped_NxN(const int N, const float *im, const float *filter_ptr, float *out, const int outsize) { const int NN=N*N; for (int j = 0; j < outsize; j += 8) { float *c = out+j; for(int i=0; i<NN; i++) { const float f = filter_ptr[i]; c[0]+=im[0]*f; c[1]+=im[1]*f; c[2]+=im[2]*f; c[3]+=im[3]*f; c[4]+=im[4]*f; c[5]+=im[5]*f; c[6]+=im[6]*f; c[7]+=im[7]*f; im+=8; } } } #ifdef MOJO_AVX inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 32; } _mm256_zeroupper(); } inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); for (int j = 0; j < outsize; j += 8)//stride) // intput w { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 72; } _mm256_zeroupper(); } inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]); const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]); const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]); const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]); for (int j = 0; j < outsize; j += 8)//stride) // intput w { __m256 a, c0, c1; // multiply filter a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1); // add result to output a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 128; } _mm256_zeroupper(); } inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); const __m256 f0 = _mm256_broadcast_ss(&filter_ptr[0]); const __m256 f1 = _mm256_broadcast_ss(&filter_ptr[1]); const __m256 f2 = _mm256_broadcast_ss(&filter_ptr[2]); const __m256 f3 = _mm256_broadcast_ss(&filter_ptr[3]); const __m256 f4 = _mm256_broadcast_ss(&filter_ptr[4]); const __m256 f5 = _mm256_broadcast_ss(&filter_ptr[5]); const __m256 f6 = _mm256_broadcast_ss(&filter_ptr[6]); const __m256 f7 = _mm256_broadcast_ss(&filter_ptr[7]); const __m256 f8 = _mm256_broadcast_ss(&filter_ptr[8]); const __m256 f9 = _mm256_broadcast_ss(&filter_ptr[9]); const __m256 f10 = _mm256_broadcast_ss(&filter_ptr[10]); const __m256 f11 = _mm256_broadcast_ss(&filter_ptr[11]); const __m256 f12 = _mm256_broadcast_ss(&filter_ptr[12]); const __m256 f13 = _mm256_broadcast_ss(&filter_ptr[13]); const __m256 f14 = _mm256_broadcast_ss(&filter_ptr[14]); const __m256 f15 = _mm256_broadcast_ss(&filter_ptr[15]); const __m256 f16 = _mm256_broadcast_ss(&filter_ptr[16]); const __m256 f17 = _mm256_broadcast_ss(&filter_ptr[17]); const __m256 f18 = _mm256_broadcast_ss(&filter_ptr[18]); const __m256 f19 = _mm256_broadcast_ss(&filter_ptr[19]); const __m256 f20 = _mm256_broadcast_ss(&filter_ptr[20]); const __m256 f21 = _mm256_broadcast_ss(&filter_ptr[21]); const __m256 f22 = _mm256_broadcast_ss(&filter_ptr[22]); const __m256 f23 = _mm256_broadcast_ss(&filter_ptr[23]); const __m256 f24 = _mm256_broadcast_ss(&filter_ptr[24]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f0); a = _mm256_load_ps(_img + 8); c1 = _mm256_mul_ps(a, f1); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 16); c1 = _mm256_mul_ps(a, f2); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 24); c1 = _mm256_mul_ps(a, f3); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 32); c1 = _mm256_mul_ps(a, f4); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 40); c1 = _mm256_mul_ps(a, f5); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 48); c1 = _mm256_mul_ps(a, f6); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 56); c1 = _mm256_mul_ps(a, f7); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 64); c1 = _mm256_mul_ps(a, f8); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 72); c1 = _mm256_mul_ps(a, f9); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 80); c1 = _mm256_mul_ps(a, f10); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 88); c1 = _mm256_mul_ps(a, f11); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 96); c1 = _mm256_mul_ps(a, f12); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 104); c1 = _mm256_mul_ps(a, f13); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 112); c1 = _mm256_mul_ps(a, f14); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 120); c1 = _mm256_mul_ps(a, f15); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 128); c1 = _mm256_mul_ps(a, f16); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 136); c1 = _mm256_mul_ps(a, f17); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 144); c1 = _mm256_mul_ps(a, f18); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 152); c1 = _mm256_mul_ps(a, f19); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 160); c1 = _mm256_mul_ps(a, f20); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 168); c1 = _mm256_mul_ps(a, f21); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 176); c1 = _mm256_mul_ps(a, f22); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 184); c1 = _mm256_mul_ps(a, f23); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(_img + 192); c1 = _mm256_mul_ps(a, f24); c0 = _mm256_add_ps(c0, c1); a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 200; } _mm256_zeroupper(); } inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize) { _mm256_zeroupper(); __m256 f[49];//=new __m256(s); for(int i=0; i<49; i++) f[i]= _mm256_broadcast_ss(&filter_ptr[i]); for (int j = 0; j < outsize; j += 8) { __m256 a, c0, c1; a = _mm256_load_ps(_img); c0 = _mm256_mul_ps(a, f[0]); for(int i=1; i<49;i++) { a = _mm256_load_ps(_img + 8*i); c1 = _mm256_mul_ps(a, f[i]); c0 = _mm256_add_ps(c0, c1); } a = _mm256_load_ps(out + j); c0 = _mm256_add_ps(c0, a); _mm256_stream_ps(out + j, c0); _img += 49*8; } _mm256_zeroupper(); //delete [] f; } #else // no AVX inline void dotsum_unwrapped_2x2(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(2, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_3x3(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(3, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_4x4(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(4, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_5x5(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(5, _img, filter_ptr, out, outsize); } inline void dotsum_unwrapped_7x7(const float *_img, const float *filter_ptr, float *out, const int outsize) { dotsum_unwrapped_NxN(7, _img, filter_ptr, out, outsize); } #endif // matrix class --------------------------------------------------- // should use opencv if available // class matrix { int _size; int _capacity; float *_x_mem; void delete_x() { delete[] _x_mem; x = NULL; _x_mem = NULL; } // 4 extra for alignment and 4 for 3 padding for SSE //float *new_x(const int size) { _x_mem = new float[size + 4+3]; x = (float *)(((uintptr_t)_x_mem + 16) & ~(uintptr_t)0x0F); return x; } // avx mem aligment float *new_x(const int size) { _x_mem = new float[size + 8 + 7]; x = (float *)(((uintptr_t)_x_mem + 32) & ~(uintptr_t)0x1F); return x; } public: std::string _name; int cols, rows, chans; int chan_stride; int chan_aligned; float *x; // size must be divisible by 8 for AVX virtual int calc_chan_stride(int w, int h) { if (chan_aligned) { int s = w*h; const int remainder = s % 8; if (remainder > 0) s += 8 - remainder; return s; } else return w*h; } matrix( ): cols(0), rows(0), chans(0), _size(0), _capacity(0), chan_stride(0), x(NULL), chan_aligned(0)/*, empty_chan(NULL)*/{} matrix( int _w, int _h, int _c=1, const float *data=NULL, int align_chan=0): cols(_w), rows(_h), chans(_c) { chan_aligned = align_chan; chan_stride = calc_chan_stride(cols, rows); _size= chan_stride*chans; _capacity=_size; x = new_x(_size); if(data!=NULL) memcpy(x,data,_size*sizeof(float)); } // copy constructor - deep copy matrix( const matrix &m) : cols(m.cols), rows(m.rows), chan_aligned(m.chan_aligned), chans(m.chans), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size) {x = new_x(_size); memcpy(x,m.x,sizeof(float)*_size); /*empty_chan = new unsigned char[chans]; memcpy(empty_chan, m.empty_chan, chans);*/} // { v=m.v; x=(float*)v.data();} // copy and pad constructor matrix( const matrix &m, int pad_cols, int pad_rows, mojo::pad_type padding= mojo::zero, int threads=1) : cols(m.cols), rows(m.rows), chans(m.chans), chan_aligned(m.chan_aligned), chan_stride(m.chan_stride), _size(m._size), _capacity(m._size) { x = new_x(_size); memcpy(x, m.x, sizeof(float)*_size); *this = pad(pad_cols, pad_rows, padding, threads); } ~matrix() { if (x) delete_x(); } matrix get_chans(int start_channel, int num_chans=1) const { return matrix(cols,rows,num_chans,&x[start_channel*chan_stride]); } // if edge_pad==0, then the padded area is just 0. // if edge_pad==1 it fills with edge pixel colors // if edge_pad==2 it fills with median edge pixel color matrix pad(int dx, int dy, mojo::pad_type edge_pad = mojo::zero, int threads=1) const { return pad(dx, dy, dx, dy, edge_pad, threads); } matrix pad(int dx, int dy, int dx_right, int dy_bottom, mojo::pad_type edge_pad = mojo::zero, int threads=1) const { matrix v(cols+dx+dx_right,rows+dy+dy_bottom,chans);//,NULL,this->chan_aligned); v.fill(0); //float *new_x = new float[chans*w*h]; #pragma omp parallel for num_threads(threads) for(int k=0; k<chans; k++) { const int v_chan_offset=k*v.chan_stride; const int chan_offset=k*chan_stride; // find median color of perimeter float median = 0.f; if (edge_pad == mojo::median_edge) { int perimeter = 2 * (cols + rows - 2); std::vector<float> d(perimeter); for (int i = 0; i < cols; i++) { d[i] = x[i+ chan_offset]; d[i + cols] = x[i + cols*(rows - 1)+ chan_offset]; } for (int i = 1; i < (rows - 1); i++) { d[i + cols * 2] = x[cols*i+ chan_offset]; // file from back so i dont need to cal index d[perimeter - i] = x[cols - 1 + cols*i+ chan_offset]; } std::nth_element(d.begin(), d.begin() + perimeter / 2, d.end()); median = d[perimeter / 2]; //for (int i = 0; i < v.rows*v.cols; i++) v.x[v_chan_offset + i] = solid_fill; } for(int j=0; j<rows; j++) { memcpy(&v.x[dx+(j+dy)*v.cols+v_chan_offset], &x[j*cols+chan_offset], sizeof(float)*cols); if(edge_pad== mojo::edge) { // do left/right side for(int i=0; i<dx; i++) v.x[i+(j+dy)*v.cols+v_chan_offset]=x[0+j*cols+chan_offset]; for (int i = 0; i<dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = x[(cols - 1) + j*cols + chan_offset]; } else if (edge_pad == mojo::median_edge) { for (int i = 0; i < dx; i++) v.x[i + (j + dy)*v.cols + v_chan_offset] = median; for (int i = 0; i < dx_right; i++) v.x[i + dx + cols + (j + dy)*v.cols + v_chan_offset] = median; } } // top bottom pad if(edge_pad== mojo::edge) { for(int j=0; j<dy; j++) memcpy(&v.x[(j)*v.cols+v_chan_offset],&v.x[(dy)*v.cols+v_chan_offset], sizeof(float)*v.cols); for (int j = 0; j<dy_bottom; j++) memcpy(&v.x[(j + dy + rows)*v.cols + v_chan_offset], &v.x[(rows - 1 + dy)*v.cols + v_chan_offset], sizeof(float)*v.cols); } if (edge_pad == mojo::median_edge) { for (int j = 0; j<dy; j++) for (int i = 0; i<v.cols; i++) v.x[i + j*v.cols + v_chan_offset] = median; for (int j = 0; j<dy_bottom; j++) for (int i = 0; i<v.cols; i++) v.x[i + (j + dy + rows)*v.cols + v_chan_offset] = median; } } return v; } matrix crop(int dx, int dy, int w, int h, int threads=1) const { matrix v(w,h,chans); #pragma omp parallel for num_threads(threads) for(int k=0; k<chans; k++) { for(int j=0; j<h; j++) { memcpy(&v.x[j*w+k*v.chan_stride], &x[dx+(j+dy)*cols+k*chan_stride], sizeof(float)*w); } } return v; } mojo::matrix shift(int dx, int dy, mojo::pad_type edge_pad=mojo::zero) { int orig_cols=cols; int orig_rows=rows; int off_x=abs(dx); int off_y=abs(dy); mojo::matrix shifted= pad(off_x, off_y, edge_pad); return shifted.crop(off_x-dx, off_y-dy,orig_cols,orig_rows); } mojo::matrix flip_cols() { mojo::matrix v(cols,rows,chans); for(int k=0; k<chans; k++) for(int j=0; j<rows; j++) for(int i=0; i<cols; i++) v.x[i+j*cols+k*chan_stride]=x[(cols-i-1)+j*cols+k*chan_stride]; return v; } mojo::matrix flip_rows() { mojo::matrix v(cols, rows, chans); for (int k = 0; k<chans; k++) for (int j = 0; j<rows; j++) memcpy(&v.x[(rows-1-j)*cols + k*chan_stride],&x[j*cols + k*chan_stride], cols*sizeof(float)); return v; } void clip(float min, float max) { int s = chan_stride*chans; for (int i = 0; i < s; i++) { if (x[i] < min) x[i] = min; if (x[i] > max) x[i]=max; } } void min_max(float *min, float *max, int *min_i=NULL, int *max_i=NULL) { int s = rows*cols; int mini = 0; int maxi = 0; for (int c = 0; c < chans; c++) { const int t = chan_stride*c; for (int i = t; i < t+s; i++) { if (x[i] < x[mini]) mini = i; if (x[i] > x[maxi]) maxi = i; } } *min = x[mini]; *max = x[maxi]; if (min_i) *min_i = mini; if (max_i) *max_i = maxi; } float mean() { const int s = rows*cols; int cnt = 0;// channel*s; float average = 0; for (int c = 0; c < chans; c++) { const int t = chan_stride*c; for (int i = 0; i < s; i++) average += x[i + t]; } average = average / (float)(s*chans); return average; } float remove_mean(int channel) { int s = rows*cols; int offset = channel*chan_stride; float average=0; for(int i=0; i<s; i++) average+=x[i+offset]; average= average/(float)s; for(int i=0; i<s; i++) x[i+offset]-=average; return average; } float remove_mean() { float m=mean(); int s = chan_stride*chans; //int offset = channel*s; for(int i=0; i<s; i++) x[i]-=m; return m; } void fill(float val) { for(int i=0; i<_size; i++) x[i]=val; } void fill_random_uniform(float range) { std::mt19937 gen(0); std::uniform_real_distribution<float> dst(-range, range); for (int i = 0; i<_size; i++) x[i] = dst(gen); } void fill_random_normal(float std) { std::mt19937 gen(0); std::normal_distribution<float> dst(0, std); for (int i = 0; i<_size; i++) x[i] = dst(gen); } // deep copy inline matrix& operator =(const matrix &m) { resize(m.cols, m.rows, m.chans, m.chan_aligned); memcpy(x,m.x,sizeof(float)*_size); // memcpy(empty_chan, m.empty_chan, chans); return *this; } int size() const {return _size;} void resize(int _w, int _h, int _c, int align_chans=0) { chan_aligned = align_chans; int new_stride = calc_chan_stride(_w,_h); int s = new_stride*_c; if(s>_capacity) { if(_capacity>0) delete_x(); _size = s; _capacity=_size; x = new_x(_size); } cols = _w; rows = _h; chans = _c; _size = s; chan_stride = new_stride; } // dot vector to 2d mat inline matrix dot_1dx2d(const matrix &m_2d) const { mojo::matrix v(m_2d.rows, 1, 1); for(int j=0; j<m_2d.rows; j++) v.x[j]=dot(x,&m_2d.x[j*m_2d.cols],_size); return v; } // += inline matrix& operator+=(const matrix &m2){ for(int i = 0; i < _size; i++) x[i] += m2.x[i]; return *this; } // -= inline matrix& operator-=(const matrix &m2) { for (int i = 0; i < _size; i++) x[i] -= m2.x[i]; return *this; } #ifndef MOJO_AVX // *= float inline matrix operator *=(const float v) { for (int i = 0; i < _size; i++) x[i] = x[i] * v; return *this; } #else inline matrix operator *=(const float v) { __m128 b; b = _mm_set_ps(v, v, v, v); for (int j = 0; j < _size; j += 4) _mm_store_ps(x + j, _mm_mul_ps(_mm_load_ps(x + j), b)); return *this; } #endif // *= matrix inline matrix operator *=(const matrix &v) { for (int i = 0; i < _size; i++) x[i] = x[i] * v.x[i]; return *this; } inline matrix operator *(const matrix &v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] * v.x[i]; return T; } // * float inline matrix operator *(const float v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] * v; return T; } // + float inline matrix operator +(const float v) { matrix T(cols, rows, chans); for (int i = 0; i < _size; i++) T.x[i] = x[i] + v; return T; } // + inline matrix operator +(matrix m2) { matrix T(cols,rows,chans); for(int i = 0; i < _size; i++) T.x[i] = x[i] + m2.x[i]; return T; } }; }// namespace
LBCouetteSolver.h
// Copyright (C) 2015 Technische Universitaet Muenchen // This file is part of the Mamico project. For conditions of distribution // and use, please see the copyright notice in Mamico's main folder, or at // www5.in.tum.de/mamico #ifndef _MOLECULARDYNAMICS_COUPLING_SOLVERS_LBCOUETTESOLVER_H_ #define _MOLECULARDYNAMICS_COUPLING_SOLVERS_LBCOUETTESOLVER_H_ #if defined(_OPENMP) #include <omp.h> #endif #include "coupling/solvers/NumericalSolver.h" namespace coupling { namespace solvers{ class LBCouetteSolver; } } /** In our scenario, the lower wall is accelerated and the upper wall stands still. * The lower wall is located at zero height. * @brief implements a three-dimensional Lattice-Boltzmann Couette flow solver. * @author Philipp Neumann */ class coupling::solvers::LBCouetteSolver: public coupling::solvers::NumericalSolver { public: /** @brief a simple constructor * @param channelheight the width and height of the channel in y and z direction * @param wallVelocity velocity at the moving wall, refers to Couette scenario * @param dx the spacial step size, and equidistant grid is applied * @param dt the time step * @param kinVisc the kinematic viscosity of the fluid * @param plotEveryTimestep the time step interval for plotting data; * 4 means, every 4th time step is plotted * @param filestem the name of the plotted file * @param processes defines on how many processes the solver will run; * 1,1,1 - sequential run - 1,2,2 = 1*2*2 = 4 processes * @param numThreads number of OpenMP threads */ LBCouetteSolver( const double channelheight, tarch::la::Vector<3,double> wallVelocity, const double kinVisc, const double dx, const double dt, const int plotEveryTimestep, const std::string filestem, const tarch::la::Vector<3,unsigned int> processes, const unsigned int numThreads=1 ): coupling::solvers::NumericalSolver(channelheight, dx, dt, kinVisc, plotEveryTimestep, filestem, processes), _omega(1.0/(3.0*(kinVisc*dt/(dx*dx))+0.5)), _wallVelocity((dt/dx)*wallVelocity) { // return if required if (skipRank()){return;} _pdf1 = new double[19*(_domainSizeX+2)*(_domainSizeY+2)*(_domainSizeZ+2)]; _pdf2 = new double[19*(_domainSizeX+2)*(_domainSizeY+2)*(_domainSizeZ+2)]; #if defined(_OPENMP) omp_set_num_threads(numThreads); #endif #if (COUPLING_MD_DEBUG==COUPLING_MD_YES) std::cout << "Domain size=" << _domainSizeX << "," << _domainSizeY << "," << _domainSizeZ << std::endl; std::cout << "tau=" << 1.0/_omega << std::endl; std::cout << "wallVelocity=" << _wallVelocity << std::endl; for (int z = 0; z < _domainSizeZ+2; z++){ for (int y = 0; y < _domainSizeY+2; y++){ for (int x = 0; x < _domainSizeX+2; x++){ std::cout << x << "," << y << "," << z << "FLAG=" << _flag[get(x,y,z)] << std::endl; }}} #endif // check pointers if ( (_pdf1==NULL) || (_pdf2==NULL) || (_vel==NULL) || (_density==NULL) || (_flag==NULL) ){ std::cout << "ERROR LBCouetteSolver: NULL ptr!" << std::endl; exit(EXIT_FAILURE); } #if (COUPLING_MD_PARALLEL==COUPLING_MD_YES) if ( (_sendBufferX==NULL) || (_recvBufferX==NULL) || (_sendBufferY==NULL) || (_recvBufferY==NULL) || (_sendBufferZ==NULL) || (_recvBufferZ==NULL) ){ std::cout << "ERROR LBCouetteSolver: NULL ptr in send/recv!" << std::endl; exit(EXIT_FAILURE); } #endif // init everything with lattice weights #pragma omp parallel for for (int i = 0; i < (_domainSizeX+2)*(_domainSizeY+2)*(_domainSizeZ+2); i++){ for (int q = 0; q < 19; q++){ _pdf1[get(i)*19+q] = _W[q]; _pdf2[get(i)*19+q] = _W[q]; } } } /** @brief a simple destructor */ virtual ~LBCouetteSolver(){ if (_pdf1!=NULL){delete [] _pdf1; _pdf1=NULL;} if (_pdf2!=NULL){delete [] _pdf2; _pdf2=NULL;} if (_vel !=NULL){delete [] _vel; _vel=NULL;} if (_density!=NULL){delete [] _density; _density=NULL;} if (_flag!=NULL){delete [] _flag; _flag=NULL;} #if (COUPLING_MD_PARALLEL==COUPLING_MD_YES) if (_sendBufferX!=NULL){delete [] _sendBufferX; _sendBufferX=NULL;} if (_sendBufferY!=NULL){delete [] _sendBufferY; _sendBufferY=NULL;} if (_sendBufferZ!=NULL){delete [] _sendBufferZ; _sendBufferZ=NULL;} if (_recvBufferX!=NULL){delete [] _recvBufferX; _recvBufferX=NULL;} if (_recvBufferY!=NULL){delete [] _recvBufferY; _recvBufferY=NULL;} if (_recvBufferZ!=NULL){delete [] _recvBufferZ; _recvBufferZ=NULL;} #endif } /** @brief advances one time step dt in time and triggers vtk plot if required */ void advance(double dt) override { if (skipRank()){return;} const int timesteps=floor( dt/_dt+0.5 ); if ( fabs(timesteps*_dt-dt)/_dt > 1.0e-8 ){std::cout << "ERROR LBCouetteSolver::advance(): time steps and dt do not match!" << std::endl; exit(EXIT_FAILURE);} for (int i = 0; i < timesteps; i++){ plot(); collidestream(); communicate(); // exchange between neighbouring MPI subdomains _counter++; } } /** @brief applies the values received from the MD-solver within the conntinuum solver * @param recvBuffer holds the data from the md solver * @param recvIndice the indices to connect the data from the buffer with macroscopic cells * @param indexConversion instance of the indexConversion */ void setMDBoundaryValues( std::vector<coupling::datastructures::MacroscopicCell<3>* >& recvBuffer,const unsigned int * const recvIndices, const coupling::IndexConversion<3>& indexConversion)override{ if (skipRank()){return ;} // loop over all received cells const unsigned int size = (unsigned int) recvBuffer.size(); for (unsigned int i = 0; i < size; i++){ // determine cell index of this cell in LB domain tarch::la::Vector<3,unsigned int> globalCellCoords = indexConversion.getGlobalVectorCellIndex(recvIndices[i]); globalCellCoords[0] = (globalCellCoords[0]+_offset[0]) - _coords[0]*_avgDomainSizeX; globalCellCoords[1] = (globalCellCoords[1]+_offset[1]) - _coords[1]*_avgDomainSizeY; globalCellCoords[2] = (globalCellCoords[2]+_offset[2]) - _coords[2]*_avgDomainSizeZ; #if (COUPLING_MD_DEBUG==COUPLING_MD_YES) std::cout << "Process coords: " << _coords << ": GlobalCellCoords for index " << indexConversion.getGlobalVectorCellIndex(recvIndices[i]) << ": " << globalCellCoords << std::endl; #endif const int index = get(globalCellCoords[0],globalCellCoords[1],globalCellCoords[2]); #if (COUPLING_MD_DEBUG==COUPLING_MD_YES) if (_flag[index]!=MD_BOUNDARY){std::cout << "ERROR LBCouetteSolver::setMDBoundaryValues(): Cell " << index << " is no MD boundary cell!" << std::endl; exit(EXIT_FAILURE);} #endif // set velocity value and pdfs in MD boundary cell (before streaming); the boundary velocities are interpolated between the neighbouring and this cell. This interpolation is valid for // FLUID-MD_BOUNDARY neighbouring relations only. // determine local velocity received from MaMiCo and convert it to LB units; store the velocity in _vel tarch::la::Vector<3,double> localVel( (1.0/recvBuffer[i]->getMacroscopicMass())*(_dt/_dx)*recvBuffer[i]->getMacroscopicMomentum()); for (unsigned int d = 0; d<3; d++){ _vel[3*index+d] = localVel[d]; } // loop over all pdfs and set them according to interpolated moving-wall conditions for (unsigned int q = 0; q < 19; q++){ // index of neighbour cell; only if cell is located inside local domain if ( ((int)globalCellCoords[0]+_C[q][0] > 0) && ((int)globalCellCoords[0]+_C[q][0]<_domainSizeX+1) && ((int)globalCellCoords[1]+_C[q][1] > 0) && ((int)globalCellCoords[1]+_C[q][1]<_domainSizeY+1) && ((int)globalCellCoords[2]+_C[q][2] > 0) && ((int)globalCellCoords[2]+_C[q][2]<_domainSizeZ+1)){ const int nbIndex = get((_C[q][0]+globalCellCoords[0]),(_C[q][1]+globalCellCoords[1]),(_C[q][2]+globalCellCoords[2])); const tarch::la::Vector<3,double> interpolVel(0.5*(_vel[3*index]+_vel[3*nbIndex]),0.5*(_vel[3*index+1]+_vel[3*nbIndex+1]),0.5*(_vel[3*index+2]+_vel[3*nbIndex+2])); _pdf1[19*index+q] = _pdf1[19*nbIndex+18-q] - 6.0*_W[q]*_density[nbIndex]*(_C[18-q][0]*interpolVel[0]+_C[18-q][1]*interpolVel[1]+_C[18-q][2]*interpolVel[2]); } } } } /** @brief returns velocity at a certain position * @param pos position for which the velocity will be returned * @returns the velocity vector for the position */ tarch::la::Vector<3,double> getVelocity(tarch::la::Vector<3,double> pos) const override { tarch::la::Vector<3,unsigned int> coords; const tarch::la::Vector<3,double> domainOffset(_coords[0]*_dx*_avgDomainSizeX,_coords[1]*_dx*_avgDomainSizeY,_coords[2]*_dx*_avgDomainSizeZ); // check pos-data for process locality (todo: put this in debug mode in future releases) if ( (pos[0]<domainOffset[0]) || (pos[0]>domainOffset[0]+_domainSizeX*_dx) || (pos[1]<domainOffset[1]) || (pos[1]>domainOffset[1]+_domainSizeY*_dx) || (pos[2]<domainOffset[2]) || (pos[2]>domainOffset[2]+_domainSizeZ*_dx) ){ std::cout << "ERROR LBCouetteSolver::getVelocity(): Position " << pos << " out of range!" << std::endl; exit(EXIT_FAILURE); } // compute index for respective cell (_dx+... for ghost cells); use coords to store local cell coordinates for (unsigned int d = 0; d < 3; d++){ coords[d] = (unsigned int) ((_dx+pos[d]-domainOffset[d])/_dx);} const int index = get(coords[0],coords[1],coords[2]); tarch::la::Vector<3,double> vel(0.0); // extract and scale velocity to "real"=MD units for (int d = 0; d < 3; d++){ vel[d] = _dx/_dt*_vel[3*index+d]; } #if (COUPLING_MD_DEBUG==COUPLING_MD_YES) std::cout << "Position " << pos << " corresponds to cell: " << coords << "; vel=" << vel << std::endl; #endif return vel; } /** @brief returns density at a certain position * @param pos position for which the density will be returned * @returns the density vector for the position */ double getDensity(tarch::la::Vector<3,double> pos) const override{ tarch::la::Vector<3,unsigned int> coords; const tarch::la::Vector<3,double> domainOffset(_coords[0]*_dx*_avgDomainSizeX,_coords[1]*_dx*_avgDomainSizeY,_coords[2]*_dx*_avgDomainSizeZ); // check pos-data for process locality (todo: put this in debug mode in future releases) if ( (pos[0]<domainOffset[0]) || (pos[0]>domainOffset[0]+_domainSizeX*_dx) || (pos[1]<domainOffset[1]) || (pos[1]>domainOffset[1]+_domainSizeY*_dx) || (pos[2]<domainOffset[2]) || (pos[2]>domainOffset[2]+_domainSizeZ*_dx) ){ std::cout << "ERROR LBCouetteSolver::getDensity(): Position " << pos << " out of range!" << std::endl; exit(EXIT_FAILURE); } // compute index for respective cell (_dx+... for ghost cells); use coords to store local cell coordinates for (unsigned int d = 0; d < 3; d++){ coords[d] = (unsigned int) ((_dx+pos[d]-domainOffset[d])/_dx);} const int index = get(coords[0],coords[1],coords[2]); return _density[index]; } /** @brief changes the velocity at the moving wall (z=0) * @param wallVelocity the velocity will be set at the moving wall */ virtual void setWallVelocity(const tarch::la::Vector<3,double> wallVelocity) override{ _wallVelocity = (_dt/_dx)*wallVelocity; } private: /** calls stream() and collide() and swaps the fields * @brief collide-stream algorithm for the Lattice-Boltzmann method */ void collidestream(){ #pragma omp parallel for for (int z = 1; z < _domainSizeZ+1; z++){ for (int y = 1; y < _domainSizeY+1; y++){ for (int x = 1; x < _domainSizeX+1; x++){ const int index = get(x,y,z); if (_flag[index]==FLUID){ stream(index); collide(index,x,y,z); } } } } // swap fields double *swap=_pdf1; _pdf1 = _pdf2; _pdf2 = swap; } /** @brief the stream part of the LB algorithm (from pdf1 to pdf2) */ void stream(int index){ const int pI = 19*index; for (int q = 0; q < 9; q++){ const int nb= 19*(_C[q][0]+_C[q][1]*_xO+_C[q][2]*_yO); _pdf2[pI+q] = _pdf1[pI+q-nb]; _pdf2[pI+18-q] = _pdf1[pI+18-q+nb]; } _pdf2[pI+9] = _pdf1[pI+9]; } /** @brieff the collide step within pdf2 */ void collide(int index,int x, int y, int z){ // index of start of cell-local pdfs in AoS const int pI = 19*index; // compute and store density, velocity double *vel = &_vel[3*index]; computeDensityAndVelocity(vel,_density[index],&_pdf2[pI]); // collide (BGK); always handle pdfs no. q and inv(q)=18-q in one step const double u2 = 1.0 - 1.5*(vel[0]*vel[0] + vel[1]*vel[1] + vel[2]*vel[2]); // pdf 0,18 double cu = -vel[1]-vel[2]; int nb = -_xO-_yO; double feq = _W[0]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI] -= _omega*(_pdf2[pI] - feq); boundary(_pdf2,pI,x,y,z,0,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[0]*_density[index]*cu; _pdf2[pI+18] -= _omega*(_pdf2[pI+18] - feq); boundary(_pdf2,pI,x,y,z,18,_flag[index-nb],pI-19*nb); // pdf 1,17 cu = -vel[0]-vel[2]; nb = -1-_yO; feq = _W[1]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+1] -= _omega*(_pdf2[pI+1] - feq); boundary(_pdf2,pI,x,y,z,1,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[1]*_density[index]*cu; _pdf2[pI+17] -= _omega*(_pdf2[pI+17] - feq); boundary(_pdf2,pI,x,y,z,17,_flag[index-nb],pI-19*nb); // pdf 2,16 cu = -vel[2]; nb = -_yO; feq = _W[2]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+2] -= _omega*(_pdf2[pI+2] - feq); boundary(_pdf2,pI,x,y,z,2,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[2]*_density[index]*cu; _pdf2[pI+16] -= _omega*(_pdf2[pI+16] - feq); boundary(_pdf2,pI,x,y,z,16,_flag[index-nb],pI-19*nb); // pdf 3,15 cu = vel[0]-vel[2]; nb = 1-_yO; feq = _W[3]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+3] -= _omega*(_pdf2[pI+3] - feq); boundary(_pdf2,pI,x,y,z,3,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[3]*_density[index]*cu; _pdf2[pI+15] -= _omega*(_pdf2[pI+15] - feq); boundary(_pdf2,pI,x,y,z,15,_flag[index-nb],pI-19*nb); // pdf 4,14 cu = vel[1]-vel[2]; nb = _xO-_yO; feq = _W[4]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+4] -= _omega*(_pdf2[pI+4] - feq); boundary(_pdf2,pI,x,y,z,4,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[4]*_density[index]*cu; _pdf2[pI+14] -= _omega*(_pdf2[pI+14] - feq); boundary(_pdf2,pI,x,y,z,14,_flag[index-nb],pI-19*nb); // pdf 5,13 cu = -vel[0]-vel[1]; nb = -1-_xO; feq = _W[5]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+5] -= _omega*(_pdf2[pI+5] - feq); boundary(_pdf2,pI,x,y,z,5,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[5]*_density[index]*cu; _pdf2[pI+13] -= _omega*(_pdf2[pI+13] - feq); boundary(_pdf2,pI,x,y,z,13,_flag[index-nb],pI-19*nb); // pdf 6,12 cu = -vel[1]; nb = -_xO; feq = _W[6]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+6] -= _omega*(_pdf2[pI+6] - feq); boundary(_pdf2,pI,x,y,z,6,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[6]*_density[index]*cu; _pdf2[pI+12] -= _omega*(_pdf2[pI+12] - feq); boundary(_pdf2,pI,x,y,z,12,_flag[index-nb],pI-19*nb); // pdf 7,11 cu = vel[0]-vel[1]; nb = 1-_xO; feq = _W[7]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+7] -= _omega*(_pdf2[pI+7] - feq); boundary(_pdf2,pI,x,y,z,7,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[7]*_density[index]*cu; _pdf2[pI+11] -= _omega*(_pdf2[pI+11] - feq); boundary(_pdf2,pI,x,y,z,11,_flag[index-nb],pI-19*nb); // pdf 8,10 cu = -vel[0]; nb = -1; feq = _W[8]*_density[index]*(u2 + 3.0*cu + 4.5*cu*cu); _pdf2[pI+8] -= _omega*(_pdf2[pI+8] - feq); boundary(_pdf2,pI,x,y,z,8,_flag[index+nb],pI+19*nb); feq -= 6.0*_W[8]*_density[index]*cu; _pdf2[pI+10] -= _omega*(_pdf2[pI+10] - feq); boundary(_pdf2,pI,x,y,z,10,_flag[index-nb],pI-19*nb); // pdf 9 _pdf2[pI+9] -= _omega*(_pdf2[pI+9] - _W[9]*_density[index]*u2); } /** @brief takes care of the correct boundary treatment for the LB method * @param pdf particle distribution function * @param index start index for current cell in pdf-array * @param x the position in x direction of the cell * @param y the position in y direction of the cell * @param z the position in z direction of the cell * @param q distribution function number * @param flag boundary flag of neighbouring cell * @param nbIndex index of neighbouring cell */ void boundary(double * const pdf, int index, int x, int y, int z, int q, const Flag &flag, int nbIndex){ if (flag!=FLUID){ if (flag==NO_SLIP){ // half-way bounce back pdf[nbIndex+18-q] = pdf[index+q]; } else if (flag==MOVING_WALL){ // half-way bounce back + moving wall acceleration (only x-direction for wall supported at the moment) pdf[nbIndex+18-q] = pdf[index+q] - 6.0*_W[q]*_density[index/19]*(_C[q][0]*_wallVelocity[0]+_C[q][1]*_wallVelocity[1]+_C[q][2]*_wallVelocity[2]); } else if (flag==PERIODIC){ // periodic treatment int target[3] = {x,y,z}; if (target[0]+_C[q][0]==0){target[0] = _domainSizeX+1;} else if (target[0]+_C[q][0]==_domainSizeX+1){target[0] = 0;} if (target[1]+_C[q][1]==0){target[1] = _domainSizeY+1;} else if (target[1]+_C[q][1]==_domainSizeY+1){target[1] = 0;} if (target[2]+_C[q][2]==0){target[2] = _domainSizeZ+1;} else if (target[2]+_C[q][2]==_domainSizeZ+1){target[2] = 0;} const int periodicNb = target[0] + (_domainSizeX+2)*(target[1] + (_domainSizeY+2)*target[2]); pdf[19*periodicNb+q] = pdf[index+q]; } } } /** @brief refers to the LB method; computes density and velocity on pdf * @param vel velocity * @param density density * @param pdf partial distribution function */ void computeDensityAndVelocity(double * const vel, double &density, const double * const pdf){ vel[0] = -(pdf[1]+pdf[5]+pdf[8]+pdf[11]+pdf[15]); density= pdf[3]+pdf[7]+pdf[10]+pdf[13]+pdf[17]; vel[1] = (pdf[4]+pdf[11]+pdf[12]+pdf[13]+pdf[18]) - (pdf[0]+pdf[5]+pdf[6]+pdf[7]+pdf[14]); vel[0] = density + vel[0]; density= density + pdf[0]+pdf[1]+pdf[2] + pdf[4]+pdf[5]+pdf[6] + pdf[8]+pdf[9] + pdf[11]+pdf[12] + pdf[14]+pdf[15]+pdf[16] + pdf[18]; vel[2] = (pdf[14]+pdf[15]+pdf[16]+pdf[17]+pdf[18]) - (pdf[0]+pdf[1]+pdf[2]+pdf[3]+pdf[4]); vel[0] = vel[0]/density; vel[1] = vel[1]/density; vel[2] = vel[2]/density; } /** takes care of communication across one face in one direction. * @param pdf partial distribution function * @param sendBuffer send buffer * @param recvBuffer receive buffer * @param nbFlagTo direction into which message is sent * @param nbFlagFrom direction from which message is received * @param startSend 3d coordinates that define the start of the data to be sent to neighbouring process * @param endSend 3d coordinates that define the end of the data to to be sent to neighbouring process * @param startRecv 3d coordinates that define the start of the data to be received from neighbouring process * @param endRecv 3d coordinates that define the end of the data to be received from neighbouring process */ void communicatePart(double *pdf, double *sendBuffer, double *recvBuffer, NbFlag nbFlagTo, NbFlag nbFlagFrom, tarch::la::Vector<3,int> startSend, tarch::la::Vector<3,int> endSend, tarch::la::Vector<3,int> startRecv, tarch::la::Vector<3,int> endRecv){ #if (COUPLING_MD_PARALLEL==COUPLING_MD_YES) // directions that point to LEFT/RIGHT,... -> same ordering as enums! const int directions[6][5] = { { 1, 5, 8,11,15}, { 3, 7,10,13,17}, { 4,11,12,13,18}, { 0, 5, 6, 7,14}, { 0, 1, 2, 3, 4}, {14,15,16,17,18} }; MPI_Request requests[2]; MPI_Status status[2]; tarch::la::Vector<2,int> plane; tarch::la::Vector<2,int> domainSize; // find out plane coordinates if (nbFlagTo==LEFT || nbFlagTo==RIGHT){plane[0]=1; plane[1]=2; domainSize[0] = _domainSizeY; domainSize[1] = _domainSizeZ; } else if (nbFlagTo==FRONT|| nbFlagTo==BACK) {plane[0]=0; plane[1]=2; domainSize[0] = _domainSizeX; domainSize[1] = _domainSizeZ; } else if (nbFlagTo==TOP || nbFlagTo==BOTTOM){plane[0]=0; plane[1]=1; domainSize[0] = _domainSizeX; domainSize[1] = _domainSizeY; } else { std::cout << "ERROR LBCouetteSolver::communicatePart: d >2 or d < 0!" << std::endl; exit(EXIT_FAILURE);} // extract data and write to send buffer tarch::la::Vector<3,int> coords(0); for (coords[2] = startSend[2]; coords[2] < endSend[2]; coords[2]++){ for (coords[1] = startSend[1]; coords[1] < endSend[1]; coords[1]++){ for (coords[0] = startSend[0]; coords[0] < endSend[0]; coords[0]++){ for (int q = 0; q < 5; q++){ sendBuffer[q+5*getParBuf(coords[plane[0]],coords[plane[1]],domainSize[0],domainSize[1])] = pdf[directions[nbFlagTo][q]+19*get(coords[0],coords[1],coords[2])]; } }}} // send and receive data MPI_Irecv(recvBuffer,(domainSize[0]+2)*(domainSize[1]+2)*5,MPI_DOUBLE,_parallelNeighbours[nbFlagFrom],1000,MPI_COMM_WORLD,&requests[0]); MPI_Isend(sendBuffer,(domainSize[0]+2)*(domainSize[1]+2)*5,MPI_DOUBLE,_parallelNeighbours[nbFlagTo], 1000,MPI_COMM_WORLD,&requests[1]); MPI_Waitall(2,requests,status); // write data back to pdf field if (_parallelNeighbours[nbFlagFrom]!=MPI_PROC_NULL){ for (coords[2] = startRecv[2]; coords[2] < endRecv[2]; coords[2]++){ for (coords[1] = startRecv[1]; coords[1] < endRecv[1]; coords[1]++){ for (coords[0] = startRecv[0]; coords[0] < endRecv[0]; coords[0]++){ for (int q = 0; q < 5; q++){ if (_flag[get(coords[0],coords[1],coords[2])] == PARALLEL_BOUNDARY){ pdf[directions[nbFlagTo][q]+19*get(coords[0],coords[1],coords[2])] = recvBuffer[q+5*getParBuf(coords[plane[0]],coords[plane[1]],domainSize[0],domainSize[1])]; } } }}} } #endif } /** @brief comunicates the boundary field data between the different processes */ void communicate(){ #if (COUPLING_MD_PARALLEL==COUPLING_MD_YES) // send from right to left communicatePart(_pdf1,_sendBufferX,_recvBufferX,LEFT,RIGHT, tarch::la::Vector<3,int>(1,1,1), tarch::la::Vector<3,int>(2,_domainSizeY+1,_domainSizeZ+1), tarch::la::Vector<3,int>(_domainSizeX+1,1,1),tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+1,_domainSizeZ+1)); // send from left to right communicatePart(_pdf1,_sendBufferX,_recvBufferX,RIGHT,LEFT, tarch::la::Vector<3,int>(_domainSizeX,1,1),tarch::la::Vector<3,int>(_domainSizeX+1,_domainSizeY+1,_domainSizeZ+1), tarch::la::Vector<3,int>(0,1,1), tarch::la::Vector<3,int>(1,_domainSizeY+1,_domainSizeZ+1)); // send from back to front communicatePart(_pdf1,_sendBufferY,_recvBufferY,FRONT,BACK, tarch::la::Vector<3,int>(0,1,1), tarch::la::Vector<3,int>(_domainSizeX+2,2,_domainSizeZ+1), tarch::la::Vector<3,int>(0,_domainSizeY+1,1), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+2,_domainSizeZ+1)); // send from front to back communicatePart(_pdf1,_sendBufferY,_recvBufferY,BACK,FRONT, tarch::la::Vector<3,int>(0,_domainSizeY,1), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+1,_domainSizeZ+1), tarch::la::Vector<3,int>(0,0,1), tarch::la::Vector<3,int>(_domainSizeX+2,1,_domainSizeZ+1)); // send from top to bottom communicatePart(_pdf1,_sendBufferZ,_recvBufferZ,BOTTOM,TOP, tarch::la::Vector<3,int>(0,0,1), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+2,2), tarch::la::Vector<3,int>(0,0,_domainSizeZ+1), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+2,_domainSizeZ+2)); // send from bottom to top communicatePart(_pdf1,_sendBufferZ,_recvBufferZ,TOP,BOTTOM, tarch::la::Vector<3,int>(0,0,_domainSizeZ), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+2,_domainSizeZ+1), tarch::la::Vector<3,int>(0,0,0), tarch::la::Vector<3,int>(_domainSizeX+2,_domainSizeY+2,1)); #endif } /** @brief relaxation frequency */ const double _omega; /** @brief velocity of moving wall of Couette flow */ tarch::la::Vector<3,double> _wallVelocity; /** @brief partical distribution function field */ double *_pdf1{NULL}; /** @brief partial distribution function field (stores the old time step)*/ double *_pdf2{NULL}; /** @brief lattice velocities*/ const int _C[19][3]{{ 0,-1,-1}, {-1, 0,-1}, { 0, 0,-1}, { 1, 0,-1}, { 0, 1,-1}, {-1,-1, 0}, { 0,-1, 0}, { 1,-1, 0}, {-1, 0, 0}, { 0, 0, 0}, { 1, 0, 0}, {-1, 1, 0}, { 0, 1, 0}, { 1, 1, 0}, { 0,-1, 1}, {-1, 0, 1}, { 0, 0, 1}, { 1, 0, 1}, { 0, 1, 1}}; /** @brief lattice weights */ const double _W[19]{1.0/36.0, 1.0/36.0, 1.0/18.0, 1.0/36.0, 1.0/36.0, 1.0/36.0, 1.0/18.0, 1.0/36.0, 1.0/18.0, 1.0/ 3.0, 1.0/18.0, 1.0/36.0, 1.0/18.0, 1.0/36.0, 1.0/36.0, 1.0/36.0, 1.0/18.0, 1.0/36.0, 1.0/36.0}; }; #endif // _MOLECULARDYNAMICS_COUPLING_SOLVERS_LBCOUETTESOLVER_H_
trmm_x_sky_u_hi_col_conj.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *mat, const ALPHA_Number *x, const ALPHA_INT columns, const ALPHA_INT ldx, const ALPHA_Number beta, ALPHA_Number *y, const ALPHA_INT ldy) { #ifdef COMPLEX ALPHA_INT num_threads = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT i = 0; i < mat->rows; i++) for(ALPHA_INT j = 0; j < columns; j++) alpha_mul(y[index2(j, i, ldy)], y[index2(j, i, ldy)], beta); #ifdef _OPENMP #pragma omp parallel for num_threads(num_threads) #endif for (ALPHA_INT cc = 0; cc < columns; ++cc) { for (ALPHA_INT cr = 0; cr < mat->rows; ++cr) { ALPHA_INT start = mat->pointers[cr]; ALPHA_INT end = mat->pointers[cr + 1]; ALPHA_INT idx = 1; ALPHA_INT eles_num = end - start; for (ALPHA_INT ai = start; ai < end; ++ai) { ALPHA_INT ac = cr - eles_num + idx; if (ac < cr) { ALPHA_Number t; alpha_mul_3c(t, alpha, mat->values[ai]); alpha_madde(y[index2(cc, cr, ldy)], t, x[index2(cc, ac, ldx)]); } else if(ac == cr) alpha_madde(y[index2(cc, cr, ldy)], alpha, x[index2(cc, ac, ldx)]); idx++; } } } return ALPHA_SPARSE_STATUS_SUCCESS; #else return ALPHA_SPARSE_STATUS_INVALID_VALUE; #endif }
matrix_multiplication.c
/****************************************************************************** * FILE: omp_mm.c * DESCRIPTION: * OpenMp Example - Matrix Multiply - C Version * Demonstrates a matrix multiply using OpenMP. Threads share row iterations * according to a predefined chunk size. ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> #define NRA 62 /* number of rows in matrix A */ #define NCA 15 /* number of columns in matrix A */ #define NCB 7 /* number of columns in matrix B */ int main (int argc, char *argv[]) { int tid, nthreads, i, j, k, chunk; double a[NRA][NCA]; /* matrix A to be multiplied */ double b[NCA][NCB]; /* matrix B to be multiplied */ double c[NRA][NCB]; /* result matrix C */ double t1, t2; chunk = 10; /* set loop iteration chunk size */ t1 = omp_get_wtime(); /*** Spawn a parallel region explicitly scoping all variables ***/ #pragma omp parallel shared(a, b, c, nthreads, chunk) private(tid, i, j, k) { tid = omp_get_thread_num(); if (tid == 0) { nthreads = omp_get_num_threads(); printf("Starting matrix multiple example with %d threads\n", nthreads); printf("Initializing matrices...\n"); } #pragma omp sections nowait { /*** Initialize matrices ***/ #pragma omp section for (i = 0; i < NRA; i++) { for (j = 0; j < NCA; j++) { a[i][j] = i + j; } } #pragma omp section for (i = 0; i < NCA; i++) { for (j = 0; j < NCB; j++) { b[i][j] = i * j; } } #pragma omp section for (i = 0; i < NRA; i++) { for (j = 0; j < NCB; j++) { c[i][j] = 0; } } } /*** Do matrix multiply sharing iterations on outer loop ***/ /*** Display who does which iterations for demonstration purposes ***/ printf("Thread %d starting matrix multiply...\n", tid); #pragma omp for schedule (static, chunk) for (i = 0; i < NRA; i++) { printf("Thread=%d did row=%d\n", tid, i); for(j = 0; j < NCB; j++) { for (k = 0; k < NCA; k++) { c[i][j] += a[i][k] * b[k][j]; } } } } /*** End of parallel region ***/ t2 = omp_get_wtime(); /*** Print results ***/ printf("******************************************************\n"); printf("Result Matrix:\n"); for (i = 0; i < NRA; i++) { for (j = 0; j < NCB; j++) { printf("%6.2f ", c[i][j]); } printf("\n"); } printf("******************************************************\n"); printf("Execution time %g\n", t2 - t1); printf ("Done.\n"); return 0; }
dem_structures_coupling_utilities.h
/* * Author: Miguel Angel Celigueta * * maceli@cimne.upc.edu */ #ifndef KRATOS_STRUCTURES_DEM_COUPLING_UTILITIES_H #define KRATOS_STRUCTURES_DEM_COUPLING_UTILITIES_H // /* External includes */ // System includes // Project includes #include "includes/variables.h" /* System includes */ #include <limits> #include <iostream> #include <iomanip> /* External includes */ #ifdef _OPENMP #include <omp.h> #endif /* Project includes */ #include "includes/define.h" #include "includes/model_part.h" #include "custom_conditions/RigidFace.h" #include "custom_conditions/RigidEdge.h" #include "DEM_application_variables.h" #include "dem_structures_coupling_application_variables.h" #include "custom_elements/spheric_continuum_particle.h" namespace Kratos { class DemStructuresCouplingUtilities { public: typedef ModelPart::NodesContainerType::ContainerType::iterator NodesIteratorType; KRATOS_CLASS_POINTER_DEFINITION(DemStructuresCouplingUtilities); /// Default constructor DemStructuresCouplingUtilities(){} /// Destructor virtual ~DemStructuresCouplingUtilities(){} //*************************************************************************************************************** //*************************************************************************************************************** void TransferStructuresSkinToDem(ModelPart& r_source_model_part, ModelPart& r_destination_model_part, Properties::Pointer props) { std::string error = CheckProvidedProperties(props); const int dimension = r_source_model_part.GetProcessInfo()[DOMAIN_SIZE]; if (error != "all_ok") KRATOS_ERROR << "The Dem Walls ModelPart has no valid Properties. Missing " << error << " . Exiting." << std::endl; r_destination_model_part.Conditions().Sort(); int id = 1; if (r_destination_model_part.Conditions().size()) id = (r_destination_model_part.ConditionsEnd()-1)->Id() + 1; ModelPart::ConditionsContainerType& source_conditions = r_source_model_part.Conditions(); // Adding conditions for (unsigned int i = 0; i < source_conditions.size(); i++) { ModelPart::ConditionsContainerType::iterator it = r_source_model_part.ConditionsBegin() + i; Geometry< Node<3> >::Pointer p_geometry = it->pGetGeometry(); Condition::Pointer cond; if (dimension == 2) { cond = Condition::Pointer(new RigidEdge2D(id, p_geometry, props)); } else { cond = Condition::Pointer(new RigidFace3D(id, p_geometry, props)); } cond->Set(DEMFlags::STICKY, true); r_destination_model_part.AddCondition(cond); //TODO: add all of them in a single sentence! AddConditions. Use a temporary PointerVector as a list (not std::vector!). id++; } // Adding nodes r_destination_model_part.AddNodes(r_source_model_part.NodesBegin(), r_source_model_part.NodesEnd()); } std::string CheckProvidedProperties(Properties::Pointer props) { std::vector<const Variable<double>* > list_of_variables_double_to_check = {&STATIC_FRICTION, &DYNAMIC_FRICTION, &FRICTION_DECAY, &WALL_COHESION, &SEVERITY_OF_WEAR, &IMPACT_WEAR_SEVERITY, &BRINELL_HARDNESS, &YOUNG_MODULUS, &POISSON_RATIO}; std::vector<const Variable<bool>* > list_of_variables_bool_to_check = {&COMPUTE_WEAR}; for (int i=0; i<(int)list_of_variables_double_to_check.size(); i++) { if(!props->Has(*list_of_variables_double_to_check[i])) return list_of_variables_double_to_check[i]->Name(); } for (int i=0; i<(int)list_of_variables_bool_to_check.size(); i++) { if(!props->Has(*list_of_variables_bool_to_check[i])) return list_of_variables_bool_to_check[i]->Name(); } return "all_ok"; } void SmoothLoadTrasferredToFem(ModelPart& r_model_part, const double portion_of_the_force_which_is_new) { #pragma omp parallel for for (int i=0; i<(int)r_model_part.Nodes().size(); i++) { auto node_it = r_model_part.NodesBegin() + i; array_1d<double, 3> averaged_force; array_1d<double, 3>& node_dem_load = node_it->FastGetSolutionStepValue(DEM_SURFACE_LOAD); noalias(averaged_force) = portion_of_the_force_which_is_new * node_dem_load + (1.0 - portion_of_the_force_which_is_new) * node_it->FastGetSolutionStepValue(DEM_SURFACE_LOAD, 1); noalias(node_dem_load) = averaged_force; } } void ComputeSandProduction(ModelPart& dem_model_part, ModelPart& outer_walls_model_part, const double time) { const std::string sand_prod_filename = "sand_production_graph.txt"; static std::ofstream ofs_sand_prod_file; static bool first_time_entered = true; if (first_time_entered) { ofs_sand_prod_file.open(sand_prod_filename, std::ofstream::out | std::ofstream::trunc); first_time_entered = false; } ModelPart::ElementsContainerType& pElements = dem_model_part.GetCommunicator().LocalMesh().Elements(); double current_total_mass_in_grams = 0.0; for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); if (p_sphere->Is(ISOLATED)) continue; const double particle_density = p_sphere->GetDensity(); const double particle_volume = p_sphere->CalculateVolume(); current_total_mass_in_grams += particle_volume * particle_density * 1.0e3; } static const double initial_total_mass_in_grams = current_total_mass_in_grams; const double cumulative_sand_mass_in_grams = initial_total_mass_in_grams - current_total_mass_in_grams; //ModelPart::ConditionsContainerType::iterator condition_begin = outer_walls_model_part.ConditionsBegin(); //const double face_pressure_in_psi = condition_begin->GetValue(POSITIVE_FACE_PRESSURE) * 0.000145; ProcessInfo& r_process_info = dem_model_part.GetProcessInfo(); const double Pascals_to_psi_factor = 0.000145; const double face_pressure_in_psi = fabs(r_process_info[TARGET_STRESS_Z]) * Pascals_to_psi_factor; static std::ofstream sand_prod_file("sand_production_graph.txt", std::ios_base::out | std::ios_base::app); sand_prod_file << time << " " << face_pressure_in_psi << " " << cumulative_sand_mass_in_grams << '\n'; sand_prod_file.flush(); } void MarkBrokenSpheres(ModelPart& dem_model_part) { ModelPart::ElementsContainerType& pElements = dem_model_part.GetCommunicator().LocalMesh().Elements(); for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericContinuumParticle* p_sphere = dynamic_cast<SphericContinuumParticle*>(raw_p_element); if (p_sphere->Is(ISOLATED)) continue; bool go_to_next_particle = false; for (unsigned int i = 0; i < p_sphere->mContinuumInitialNeighborsSize; i++) { if (!p_sphere->mIniNeighbourFailureId[i]) { go_to_next_particle = true; break; } } if (go_to_next_particle) continue; else p_sphere->Set(ISOLATED, true); } } void ComputeSandProductionWithDepthFirstSearchNonRecursiveImplementation(ModelPart& dem_model_part, ModelPart& outer_walls_model_part, const double time) { const std::string sand_prod_filename = "sand_production_graph_with_chunks_non_recursive.txt"; static std::ofstream ofs_sand_prod_file; const std::string granulometry_distr_filename = "granulometry_distribution.txt"; static std::ofstream ofs_granulometry_distr_file; static bool first_time_entered = true; if (first_time_entered) { ofs_sand_prod_file.open(sand_prod_filename, std::ofstream::out | std::ofstream::trunc); ofs_granulometry_distr_file.open(granulometry_distr_filename, std::ofstream::out | std::ofstream::trunc); first_time_entered = false; } ModelPart::ElementsContainerType& pElements = dem_model_part.GetCommunicator().LocalMesh().Elements(); std::vector<double> chunks_masses; for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; it->Set(VISITED, false); } std::vector<SphericContinuumParticle*> stack_of_particles_to_check; for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericContinuumParticle* p_sphere = dynamic_cast<SphericContinuumParticle*>(raw_p_element); double this_chunk_mass = 0.0; stack_of_particles_to_check.push_back(p_sphere); while (stack_of_particles_to_check.size()) { SphericContinuumParticle* current_particle = stack_of_particles_to_check.back(); stack_of_particles_to_check.pop_back(); if (current_particle->Is(VISITED)) continue; const double particle_density = current_particle->GetDensity(); const double particle_volume = current_particle->CalculateVolume(); this_chunk_mass += particle_volume * particle_density * 1.0e3; current_particle->Set(VISITED, true); for (size_t i = 0; i < current_particle->mContinuumInitialNeighborsSize; i++) { SphericParticle* p_neighbour_sphere = current_particle->mNeighbourElements[i]; if (p_neighbour_sphere == NULL) continue; if (p_neighbour_sphere->Is(VISITED)) continue; //not necessary, but saves increasing and decreasing stack_of_particles_to_check's size if (current_particle->mIniNeighbourFailureId[i]) continue; auto existing_element_it = dem_model_part.GetMesh(0).Elements().find(p_neighbour_sphere->Id()); if (existing_element_it == dem_model_part.GetMesh(0).ElementsEnd()) continue; SphericContinuumParticle* p_neigh_cont_sphere = dynamic_cast<SphericContinuumParticle*>(p_neighbour_sphere); stack_of_particles_to_check.push_back(p_neigh_cont_sphere); } } if (this_chunk_mass) chunks_masses.push_back(this_chunk_mass); } const double max_mass_of_a_single_chunck = *std::max_element(chunks_masses.begin(), chunks_masses.end()); const double current_total_mass_in_grams = max_mass_of_a_single_chunck; static const double initial_total_mass_in_grams = current_total_mass_in_grams; const double cumulative_sand_mass_in_grams = initial_total_mass_in_grams - current_total_mass_in_grams; ProcessInfo& r_process_info = dem_model_part.GetProcessInfo(); const double Pascals_to_psi_factor = 0.000145; const double face_pressure_in_psi = fabs(r_process_info[TARGET_STRESS_Z]) * Pascals_to_psi_factor; ofs_sand_prod_file << time << " " << face_pressure_in_psi << " " << cumulative_sand_mass_in_grams << '\n'; ofs_sand_prod_file.flush(); unsigned int number_of_time_steps_between_granulometry_prints = 1e9; static unsigned int printing_counter = 0; if (printing_counter == number_of_time_steps_between_granulometry_prints) { ofs_granulometry_distr_file << time; for (unsigned int k = 0; k < chunks_masses.size(); k++) ofs_granulometry_distr_file << " " << chunks_masses[k]; ofs_granulometry_distr_file << '\n'; printing_counter = 0; } printing_counter++; ofs_granulometry_distr_file.flush(); } void ComputeSandProductionWithDepthFirstSearch(ModelPart& dem_model_part, ModelPart& outer_walls_model_part, const double time) { const std::string filename = "sand_production_graph_with_chunks.txt"; std::ifstream ifile(filename.c_str()); static bool first_time_entered = true; if ((bool) ifile && first_time_entered) { std::remove(filename.c_str()); first_time_entered = false; } ModelPart::ElementsContainerType& pElements = dem_model_part.GetCommunicator().LocalMesh().Elements(); std::vector<double> chunks_masses; for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; it->Set(VISITED, false); } for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericContinuumParticle* p_sphere = dynamic_cast<SphericContinuumParticle*>(raw_p_element); double this_chunk_mass = 0.0; if( it->IsNot(VISITED) ) { DepthFirstSearchVisit(p_sphere, this_chunk_mass); chunks_masses.push_back(this_chunk_mass); } } const double max_mass_of_a_single_chunck = *std::max_element(chunks_masses.begin(), chunks_masses.end()); const double current_total_mass_in_grams = max_mass_of_a_single_chunck; static const double initial_total_mass_in_grams = current_total_mass_in_grams; const double cumulative_sand_mass_in_grams = initial_total_mass_in_grams - current_total_mass_in_grams; ModelPart::ConditionsContainerType::iterator condition_begin = outer_walls_model_part.ConditionsBegin(); const double Pascals_to_psi_factor = 0.000145; const double face_pressure_in_psi = condition_begin->GetValue(POSITIVE_FACE_PRESSURE) * Pascals_to_psi_factor; static std::ofstream sand_prod_file(filename, std::ios_base::out | std::ios_base::app); sand_prod_file << time << " " << face_pressure_in_psi << " " << cumulative_sand_mass_in_grams << '\n'; sand_prod_file.flush(); } void DepthFirstSearchVisit(SphericContinuumParticle* p_sphere, double& this_chunk_mass) { p_sphere->Set(VISITED, true); const double particle_radius = p_sphere->GetRadius(); const double particle_density = p_sphere->GetDensity(); this_chunk_mass += (4.0/3.0) * Globals::Pi * particle_density * particle_radius * particle_radius * particle_radius * 1000.0; for (size_t i=0; i<p_sphere->mContinuumInitialNeighborsSize; i++) { SphericParticle* p_neighbour_sphere = p_sphere->mNeighbourElements[i]; if (p_neighbour_sphere==NULL) continue; if (p_sphere->mIniNeighbourFailureId[i]) continue; if (p_neighbour_sphere->IsNot(VISITED)) { SphericContinuumParticle* p_neigh_cont_sphere = dynamic_cast<SphericContinuumParticle*>(p_neighbour_sphere); DepthFirstSearchVisit(p_neigh_cont_sphere, this_chunk_mass); } } } void ComputeTriaxialSandProduction(ModelPart& dem_model_part, ModelPart& outer_walls_model_part_1, ModelPart& outer_walls_model_part_2, const double time) { const std::string filename = "sand_production_graph.txt"; std::ifstream ifile(filename.c_str()); static bool first_time_entered = true; if ((bool) ifile && first_time_entered) { std::remove(filename.c_str()); first_time_entered = false; } ModelPart::ElementsContainerType& pElements = dem_model_part.GetCommunicator().LocalMesh().Elements(); double current_total_mass_in_grams = 0.0; for (unsigned int k = 0; k < pElements.size(); k++) { ModelPart::ElementsContainerType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); if (p_sphere->Is(ISOLATED)) continue; const double particle_radius = p_sphere->GetRadius(); const double particle_density = p_sphere->GetDensity(); current_total_mass_in_grams += (4.0/3.0) * Globals::Pi * particle_density * particle_radius * particle_radius * particle_radius * 1000.0; } static const double initial_total_mass_in_grams = current_total_mass_in_grams; const double cumulative_sand_mass_in_grams = initial_total_mass_in_grams - current_total_mass_in_grams; ModelPart::ConditionsContainerType::iterator condition_begin_1 = outer_walls_model_part_1.ConditionsBegin(); ModelPart::ConditionsContainerType::iterator condition_begin_2 = outer_walls_model_part_2.ConditionsBegin(); const double Pascals_to_psi_factor = 0.000145; const double face_pressure_in_psi = (condition_begin_1->GetValue(POSITIVE_FACE_PRESSURE) + condition_begin_2->GetValue(POSITIVE_FACE_PRESSURE) + 3.45e6) * Pascals_to_psi_factor * 0.33333333333333; // 3.45e6 is the sigma_z constant pressure static std::ofstream sand_prod_file(filename, std::ios_base::out | std::ios_base::app); sand_prod_file << time << " " << face_pressure_in_psi << " " << cumulative_sand_mass_in_grams << '\n'; sand_prod_file.flush(); } //*************************************************************************************************************** //*************************************************************************************************************** /// Turn back information as a stemplate<class T, std::size_t dim> tring. virtual std::string Info() const { return ""; } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const { } protected: private: /// Assignment operator DemStructuresCouplingUtilities & operator=(DemStructuresCouplingUtilities const& rOther); ///@} }; // Class DemStructuresCouplingUtilities } // namespace Python. #endif // KRATOS_STRUCTURES_DEM_COUPLING_UTILITIES_H
callback.h
#define _BSD_SOURCE #define _DEFAULT_SOURCE #include <stdio.h> #include <inttypes.h> #include <omp.h> #include <ompt.h> #include "ompt-signal.h" // Used to detect architecture #include "../../src/kmp_platform.h" static const char* ompt_thread_type_t_values[] = { NULL, "ompt_thread_initial", "ompt_thread_worker", "ompt_thread_other" }; static const char* ompt_task_status_t_values[] = { NULL, "ompt_task_complete", "ompt_task_yield", "ompt_task_cancel", "ompt_task_others" }; static const char* ompt_cancel_flag_t_values[] = { "ompt_cancel_parallel", "ompt_cancel_sections", "ompt_cancel_do", "ompt_cancel_taskgroup", "ompt_cancel_activated", "ompt_cancel_detected", "ompt_cancel_discarded_task" }; static void format_task_type(int type, char *buffer) { char *progress = buffer; if (type & ompt_task_initial) progress += sprintf(progress, "ompt_task_initial"); if (type & ompt_task_implicit) progress += sprintf(progress, "ompt_task_implicit"); if (type & ompt_task_explicit) progress += sprintf(progress, "ompt_task_explicit"); if (type & ompt_task_target) progress += sprintf(progress, "ompt_task_target"); if (type & ompt_task_undeferred) progress += sprintf(progress, "|ompt_task_undeferred"); if (type & ompt_task_untied) progress += sprintf(progress, "|ompt_task_untied"); if (type & ompt_task_final) progress += sprintf(progress, "|ompt_task_final"); if (type & ompt_task_mergeable) progress += sprintf(progress, "|ompt_task_mergeable"); if (type & ompt_task_merged) progress += sprintf(progress, "|ompt_task_merged"); } static ompt_set_callback_t ompt_set_callback; static ompt_get_callback_t ompt_get_callback; static ompt_get_state_t ompt_get_state; static ompt_get_task_info_t ompt_get_task_info; static ompt_get_thread_data_t ompt_get_thread_data; static ompt_get_parallel_info_t ompt_get_parallel_info; static ompt_get_unique_id_t ompt_get_unique_id; static ompt_get_num_procs_t ompt_get_num_procs; static ompt_get_num_places_t ompt_get_num_places; static ompt_get_place_proc_ids_t ompt_get_place_proc_ids; static ompt_get_place_num_t ompt_get_place_num; static ompt_get_partition_place_nums_t ompt_get_partition_place_nums; static ompt_get_proc_id_t ompt_get_proc_id; static ompt_enumerate_states_t ompt_enumerate_states; static ompt_enumerate_mutex_impls_t ompt_enumerate_mutex_impls; static void print_ids(int level) { int task_type, thread_num; omp_frame_t *frame; ompt_data_t *task_parallel_data; ompt_data_t *task_data; int exists_task = ompt_get_task_info(level, &task_type, &task_data, &frame, &task_parallel_data, &thread_num); char buffer[2048]; format_task_type(task_type, buffer); if (frame) printf("%" PRIu64 ": task level %d: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", exit_frame=%p, reenter_frame=%p, " "task_type=%s=%d, thread_num=%d\n", ompt_get_thread_data()->value, level, exists_task ? task_parallel_data->value : 0, exists_task ? task_data->value : 0, frame->exit_frame, frame->enter_frame, buffer, task_type, thread_num); } #define get_frame_address(level) __builtin_frame_address(level) #define print_frame(level) \ printf("%" PRIu64 ": __builtin_frame_address(%d)=%p\n", \ ompt_get_thread_data()->value, level, get_frame_address(level)) // clang (version 5.0 and above) adds an intermediate function call with debug flag (-g) #if defined(TEST_NEED_PRINT_FRAME_FROM_OUTLINED_FN) #if defined(DEBUG) && defined(__clang__) && __clang_major__ >= 5 #define print_frame_from_outlined_fn(level) print_frame(level+1) #else #define print_frame_from_outlined_fn(level) print_frame(level) #endif #if defined(__clang__) && __clang_major__ >= 5 #warning "Clang 5.0 and later add an additional wrapper for outlined functions when compiling with debug information." #warning "Please define -DDEBUG iff you manually pass in -g to make the tests succeed!" #endif #endif // This macro helps to define a label at the current position that can be used // to get the current address in the code. // // For print_current_address(): // To reliably determine the offset between the address of the label and the // actual return address, we insert a NOP instruction as a jump target as the // compiler would otherwise insert an instruction that we can't control. The // instruction length is target dependent and is explained below. // // (The empty block between "#pragma omp ..." and the __asm__ statement is a // workaround for a bug in the Intel Compiler.) #define define_ompt_label(id) \ {} \ __asm__("nop"); \ ompt_label_##id: // This macro helps to get the address of a label that is inserted by the above // macro define_ompt_label(). The address is obtained with a GNU extension // (&&label) that has been tested with gcc, clang and icc. #define get_ompt_label_address(id) (&& ompt_label_##id) // This macro prints the exact address that a previously called runtime function // returns to. #define print_current_address(id) \ define_ompt_label(id) \ print_possible_return_addresses(get_ompt_label_address(id)) #if KMP_ARCH_X86 || KMP_ARCH_X86_64 // On X86 the NOP instruction is 1 byte long. In addition, the comiler inserts // a MOV instruction for non-void runtime functions which is 3 bytes long. #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p or %p for non-void functions\n", \ ompt_get_thread_data()->value, ((char *)addr) - 1, ((char *)addr) - 4) #elif KMP_ARCH_PPC64 // On Power the NOP instruction is 4 bytes long. In addition, the compiler // inserts an LD instruction which accounts for another 4 bytes. In contrast to // X86 this instruction is always there, even for void runtime functions. #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p\n", ompt_get_thread_data()->value, \ ((char *)addr) - 8) #elif KMP_ARCH_AARCH64 // On AArch64 the NOP instruction is 4 bytes long, can be followed by inserted // store instruction (another 4 bytes long). #define print_possible_return_addresses(addr) \ printf("%" PRIu64 ": current_address=%p or %p\n", ompt_get_thread_data()->value, \ ((char *)addr) - 4, ((char *)addr) - 8) #else #error Unsupported target architecture, cannot determine address offset! #endif // This macro performs a somewhat similar job to print_current_address(), except // that it discards a certain number of nibbles from the address and only prints // the most significant bits / nibbles. This can be used for cases where the // return address can only be approximated. // // To account for overflows (ie the most significant bits / nibbles have just // changed as we are a few bytes above the relevant power of two) the addresses // of the "current" and of the "previous block" are printed. #define print_fuzzy_address(id) \ define_ompt_label(id) \ print_fuzzy_address_blocks(get_ompt_label_address(id)) // If you change this define you need to adapt all capture patterns in the tests // to include or discard the new number of nibbles! #define FUZZY_ADDRESS_DISCARD_NIBBLES 2 #define FUZZY_ADDRESS_DISCARD_BYTES (1 << ((FUZZY_ADDRESS_DISCARD_NIBBLES) * 4)) #define print_fuzzy_address_blocks(addr) \ printf("%" PRIu64 ": fuzzy_address=0x%" PRIx64 " or 0x%" PRIx64 " (%p)\n", \ ompt_get_thread_data()->value, \ ((uint64_t)addr) / FUZZY_ADDRESS_DISCARD_BYTES - 1, \ ((uint64_t)addr) / FUZZY_ADDRESS_DISCARD_BYTES, addr) static void on_ompt_callback_mutex_acquire( ompt_mutex_kind_t kind, unsigned int hint, unsigned int impl, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_wait_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_wait_nest_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_wait_critical: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_wait_atomic: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_wait_ordered: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; default: break; } } static void on_ompt_callback_mutex_acquired( ompt_mutex_kind_t kind, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_acquired_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_acquired_nest_lock_first: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_acquired_critical: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_acquired_atomic: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_acquired_ordered: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_mutex_released( ompt_mutex_kind_t kind, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_release_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_release_nest_lock_last: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_critical: printf("%" PRIu64 ": ompt_event_release_critical: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_atomic: printf("%" PRIu64 ": ompt_event_release_atomic: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_ordered: printf("%" PRIu64 ": ompt_event_release_ordered: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_nest_lock( ompt_scope_endpoint_t endpoint, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_acquired_nest_lock_next: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_release_nest_lock_prev: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; } } static void on_ompt_callback_sync_region( ompt_sync_region_kind_t kind, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_barrier_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); print_ids(0); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_taskwait_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_taskgroup_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } break; case ompt_scope_end: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_barrier_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_taskwait_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_taskgroup_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; } break; } } static void on_ompt_callback_sync_region_wait( ompt_sync_region_kind_t kind, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_wait_barrier_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_wait_taskwait_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_wait_taskgroup_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } break; case ompt_scope_end: switch(kind) { case ompt_sync_region_barrier: printf("%" PRIu64 ": ompt_event_wait_barrier_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskwait: printf("%" PRIu64 ": ompt_event_wait_taskwait_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; case ompt_sync_region_taskgroup: printf("%" PRIu64 ": ompt_event_wait_taskgroup_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, codeptr_ra); break; } break; } } static void on_ompt_callback_flush( ompt_data_t *thread_data, const void *codeptr_ra) { printf("%" PRIu64 ": ompt_event_flush: codeptr_ra=%p\n", thread_data->value, codeptr_ra); } static void on_ompt_callback_cancel( ompt_data_t *task_data, int flags, const void *codeptr_ra) { const char* first_flag_value; const char* second_flag_value; if(flags & ompt_cancel_parallel) first_flag_value = ompt_cancel_flag_t_values[0]; else if(flags & ompt_cancel_sections) first_flag_value = ompt_cancel_flag_t_values[1]; else if(flags & ompt_cancel_do) first_flag_value = ompt_cancel_flag_t_values[2]; else if(flags & ompt_cancel_taskgroup) first_flag_value = ompt_cancel_flag_t_values[3]; if(flags & ompt_cancel_activated) second_flag_value = ompt_cancel_flag_t_values[4]; else if(flags & ompt_cancel_detected) second_flag_value = ompt_cancel_flag_t_values[5]; else if(flags & ompt_cancel_discarded_task) second_flag_value = ompt_cancel_flag_t_values[6]; printf("%" PRIu64 ": ompt_event_cancel: task_data=%" PRIu64 ", flags=%s|%s=%" PRIu32 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, task_data->value, first_flag_value, second_flag_value, flags, codeptr_ra); } static void on_ompt_callback_idle( ompt_scope_endpoint_t endpoint) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_idle_begin:\n", ompt_get_thread_data()->value); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_idle_end:\n", ompt_get_thread_data()->value); break; } } static void on_ompt_callback_implicit_task( ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, unsigned int team_size, unsigned int thread_num) { switch(endpoint) { case ompt_scope_begin: if(task_data->ptr) printf("%s\n", "0: task_data initially not null"); task_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_implicit_task_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", team_size=%" PRIu32 ", thread_num=%" PRIu32 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, team_size, thread_num); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_implicit_task_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", team_size=%" PRIu32 ", thread_num=%" PRIu32 "\n", ompt_get_thread_data()->value, (parallel_data)?parallel_data->value:0, task_data->value, team_size, thread_num); break; } } static void on_ompt_callback_lock_init( ompt_mutex_kind_t kind, unsigned int hint, unsigned int impl, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_init_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_init_nest_lock: wait_id=%" PRIu64 ", hint=%" PRIu32 ", impl=%" PRIu32 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, hint, impl, codeptr_ra); break; default: break; } } static void on_ompt_callback_lock_destroy( ompt_mutex_kind_t kind, omp_wait_id_t wait_id, const void *codeptr_ra) { switch(kind) { case ompt_mutex_lock: printf("%" PRIu64 ": ompt_event_destroy_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; case ompt_mutex_nest_lock: printf("%" PRIu64 ": ompt_event_destroy_nest_lock: wait_id=%" PRIu64 ", codeptr_ra=%p \n", ompt_get_thread_data()->value, wait_id, codeptr_ra); break; default: break; } } static void on_ompt_callback_work( ompt_work_type_t wstype, ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, uint64_t count, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: switch(wstype) { case ompt_work_loop: printf("%" PRIu64 ": ompt_event_loop_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_sections: printf("%" PRIu64 ": ompt_event_sections_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_executor: printf("%" PRIu64 ": ompt_event_single_in_block_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_other: printf("%" PRIu64 ": ompt_event_single_others_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_workshare: //impl break; case ompt_work_distribute: printf("%" PRIu64 ": ompt_event_distribute_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_taskloop: //impl printf("%" PRIu64 ": ompt_event_taskloop_begin: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; } break; case ompt_scope_end: switch(wstype) { case ompt_work_loop: printf("%" PRIu64 ": ompt_event_loop_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_sections: printf("%" PRIu64 ": ompt_event_sections_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_executor: printf("%" PRIu64 ": ompt_event_single_in_block_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_single_other: printf("%" PRIu64 ": ompt_event_single_others_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_workshare: //impl break; case ompt_work_distribute: printf("%" PRIu64 ": ompt_event_distribute_end: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; case ompt_work_taskloop: //impl printf("%" PRIu64 ": ompt_event_taskloop_end: parallel_id=%" PRIu64 ", parent_task_id=%" PRIu64 ", codeptr_ra=%p, count=%" PRIu64 "\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra, count); break; } break; } } static void on_ompt_callback_master( ompt_scope_endpoint_t endpoint, ompt_data_t *parallel_data, ompt_data_t *task_data, const void *codeptr_ra) { switch(endpoint) { case ompt_scope_begin: printf("%" PRIu64 ": ompt_event_master_begin: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; case ompt_scope_end: printf("%" PRIu64 ": ompt_event_master_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, task_data->value, codeptr_ra); break; } } static void on_ompt_callback_parallel_begin( ompt_data_t *encountering_task_data, const omp_frame_t *encountering_task_frame, ompt_data_t* parallel_data, uint32_t requested_team_size, ompt_invoker_t invoker, const void *codeptr_ra) { if(parallel_data->ptr) printf("0: parallel_data initially not null\n"); parallel_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_parallel_begin: parent_task_id=%" PRIu64 ", parent_task_frame.exit=%p, parent_task_frame.reenter=%p, parallel_id=%" PRIu64 ", requested_team_size=%" PRIu32 ", codeptr_ra=%p, invoker=%d\n", ompt_get_thread_data()->value, encountering_task_data->value, encountering_task_frame->exit_frame, encountering_task_frame->enter_frame, parallel_data->value, requested_team_size, codeptr_ra, invoker); } static void on_ompt_callback_parallel_end( ompt_data_t *parallel_data, ompt_data_t *encountering_task_data, ompt_invoker_t invoker, const void *codeptr_ra) { printf("%" PRIu64 ": ompt_event_parallel_end: parallel_id=%" PRIu64 ", task_id=%" PRIu64 ", invoker=%d, codeptr_ra=%p\n", ompt_get_thread_data()->value, parallel_data->value, encountering_task_data->value, invoker, codeptr_ra); } static void on_ompt_callback_task_create( ompt_data_t *encountering_task_data, const omp_frame_t *encountering_task_frame, ompt_data_t* new_task_data, int type, int has_dependences, const void *codeptr_ra) { if(new_task_data->ptr) printf("0: new_task_data initially not null\n"); new_task_data->value = ompt_get_unique_id(); char buffer[2048]; format_task_type(type, buffer); //there is no parallel_begin callback for implicit parallel region //thus it is initialized in initial task if(type & ompt_task_initial) { ompt_data_t *parallel_data; ompt_get_parallel_info(0, &parallel_data, NULL); if(parallel_data->ptr) printf("%s\n", "0: parallel_data initially not null"); parallel_data->value = ompt_get_unique_id(); } printf("%" PRIu64 ": ompt_event_task_create: parent_task_id=%" PRIu64 ", parent_task_frame.exit=%p, parent_task_frame.reenter=%p, new_task_id=%" PRIu64 ", codeptr_ra=%p, task_type=%s=%d, has_dependences=%s\n", ompt_get_thread_data()->value, encountering_task_data ? encountering_task_data->value : 0, encountering_task_frame ? encountering_task_frame->exit_frame : NULL, encountering_task_frame ? encountering_task_frame->enter_frame : NULL, new_task_data->value, codeptr_ra, buffer, type, has_dependences ? "yes" : "no"); } static void on_ompt_callback_task_schedule( ompt_data_t *first_task_data, ompt_task_status_t prior_task_status, ompt_data_t *second_task_data) { printf("%" PRIu64 ": ompt_event_task_schedule: first_task_id=%" PRIu64 ", second_task_id=%" PRIu64 ", prior_task_status=%s=%d\n", ompt_get_thread_data()->value, first_task_data->value, second_task_data->value, ompt_task_status_t_values[prior_task_status], prior_task_status); if(prior_task_status == ompt_task_complete) { printf("%" PRIu64 ": ompt_event_task_end: task_id=%" PRIu64 "\n", ompt_get_thread_data()->value, first_task_data->value); } } static void on_ompt_callback_task_dependences( ompt_data_t *task_data, const ompt_task_dependence_t *deps, int ndeps) { printf("%" PRIu64 ": ompt_event_task_dependences: task_id=%" PRIu64 ", deps=%p, ndeps=%d\n", ompt_get_thread_data()->value, task_data->value, (void *)deps, ndeps); } static void on_ompt_callback_task_dependence( ompt_data_t *first_task_data, ompt_data_t *second_task_data) { printf("%" PRIu64 ": ompt_event_task_dependence_pair: first_task_id=%" PRIu64 ", second_task_id=%" PRIu64 "\n", ompt_get_thread_data()->value, first_task_data->value, second_task_data->value); } static void on_ompt_callback_thread_begin( ompt_thread_type_t thread_type, ompt_data_t *thread_data) { if(thread_data->ptr) printf("%s\n", "0: thread_data initially not null"); thread_data->value = ompt_get_unique_id(); printf("%" PRIu64 ": ompt_event_thread_begin: thread_type=%s=%d, thread_id=%" PRIu64 "\n", ompt_get_thread_data()->value, ompt_thread_type_t_values[thread_type], thread_type, thread_data->value); } static void on_ompt_callback_thread_end( ompt_data_t *thread_data) { printf("%" PRIu64 ": ompt_event_thread_end: thread_id=%" PRIu64 "\n", ompt_get_thread_data()->value, thread_data->value); } static int on_ompt_callback_control_tool( uint64_t command, uint64_t modifier, void *arg, const void *codeptr_ra) { omp_frame_t* omptTaskFrame; ompt_get_task_info(0, NULL, (ompt_data_t**) NULL, &omptTaskFrame, NULL, NULL); printf("%" PRIu64 ": ompt_event_control_tool: command=%" PRIu64 ", modifier=%" PRIu64 ", arg=%p, codeptr_ra=%p, current_task_frame.exit=%p, current_task_frame.reenter=%p \n", ompt_get_thread_data()->value, command, modifier, arg, codeptr_ra, omptTaskFrame->exit_frame, omptTaskFrame->enter_frame); return 0; //success } #define register_callback_t(name, type) \ do{ \ type f_##name = &on_##name; \ if (ompt_set_callback(name, (ompt_callback_t)f_##name) == \ ompt_set_never) \ printf("0: Could not register callback '" #name "'\n"); \ }while(0) #define register_callback(name) register_callback_t(name, name##_t) int ompt_initialize( ompt_function_lookup_t lookup, ompt_data_t *tool_data) { ompt_set_callback = (ompt_set_callback_t) lookup("ompt_set_callback"); ompt_get_callback = (ompt_get_callback_t) lookup("ompt_get_callback"); ompt_get_state = (ompt_get_state_t) lookup("ompt_get_state"); ompt_get_task_info = (ompt_get_task_info_t) lookup("ompt_get_task_info"); ompt_get_thread_data = (ompt_get_thread_data_t) lookup("ompt_get_thread_data"); ompt_get_parallel_info = (ompt_get_parallel_info_t) lookup("ompt_get_parallel_info"); ompt_get_unique_id = (ompt_get_unique_id_t) lookup("ompt_get_unique_id"); ompt_get_num_procs = (ompt_get_num_procs_t) lookup("ompt_get_num_procs"); ompt_get_num_places = (ompt_get_num_places_t) lookup("ompt_get_num_places"); ompt_get_place_proc_ids = (ompt_get_place_proc_ids_t) lookup("ompt_get_place_proc_ids"); ompt_get_place_num = (ompt_get_place_num_t) lookup("ompt_get_place_num"); ompt_get_partition_place_nums = (ompt_get_partition_place_nums_t) lookup("ompt_get_partition_place_nums"); ompt_get_proc_id = (ompt_get_proc_id_t) lookup("ompt_get_proc_id"); ompt_enumerate_states = (ompt_enumerate_states_t) lookup("ompt_enumerate_states"); ompt_enumerate_mutex_impls = (ompt_enumerate_mutex_impls_t) lookup("ompt_enumerate_mutex_impls"); register_callback(ompt_callback_mutex_acquire); register_callback_t(ompt_callback_mutex_acquired, ompt_callback_mutex_t); register_callback_t(ompt_callback_mutex_released, ompt_callback_mutex_t); register_callback(ompt_callback_nest_lock); register_callback(ompt_callback_sync_region); register_callback_t(ompt_callback_sync_region_wait, ompt_callback_sync_region_t); register_callback(ompt_callback_control_tool); register_callback(ompt_callback_flush); register_callback(ompt_callback_cancel); register_callback(ompt_callback_idle); register_callback(ompt_callback_implicit_task); register_callback_t(ompt_callback_lock_init, ompt_callback_mutex_acquire_t); register_callback_t(ompt_callback_lock_destroy, ompt_callback_mutex_t); register_callback(ompt_callback_work); register_callback(ompt_callback_master); register_callback(ompt_callback_parallel_begin); register_callback(ompt_callback_parallel_end); register_callback(ompt_callback_task_create); register_callback(ompt_callback_task_schedule); register_callback(ompt_callback_task_dependences); register_callback(ompt_callback_task_dependence); register_callback(ompt_callback_thread_begin); register_callback(ompt_callback_thread_end); printf("0: NULL_POINTER=%p\n", (void*)NULL); return 1; //success } void ompt_finalize(ompt_data_t *tool_data) { printf("0: ompt_event_runtime_shutdown\n"); } ompt_start_tool_result_t* ompt_start_tool( unsigned int omp_version, const char *runtime_version) { static ompt_start_tool_result_t ompt_start_tool_result = {&ompt_initialize,&ompt_finalize, 0}; return &ompt_start_tool_result; }
zSchCompUdt-2Ddynamic.c
/*! \file Copyright (c) 2003, The Regents of the University of California, through Lawrence Berkeley National Laboratory (subject to receipt of any required approvals from U.S. Dept. of Energy) All rights reserved. The source code is distributed under BSD license, see the file License.txt at the top-level directory. */ /*! @file * \brief This file contains the main loop of pdgstrf which involves rank k * update of the Schur complement. * Uses 2D partitioning for the scatter phase. * * <pre> * -- Distributed SuperLU routine (version 5.4) -- * Lawrence Berkeley National Lab, Univ. of California Berkeley. * October 1, 2014 * * Modified: * September 14, 2017 * - First gather U-panel, then depending on "ldu" (excluding leading zeros), * gather only trailing columns of the L-panel corresponding to the nonzero * of U-rows. * - Padding zeros for nice dimensions of GEMM. * * June 1, 2018 add parallel AWPM pivoting; add back arrive_at_ublock() */ #define SCHEDULE_STRATEGY guided /* * Buffers: * [ lookAhead_L_buff | Remain_L_buff ] : stores the gathered L-panel * (A matrix in C := A*B ) * bigU : stores the U-panel (B matrix in C := A*B) * bigV : stores the block GEMM result (C matrix in C := A*B) */ if ( msg0 && msg2 ) { /* L(:,k) and U(k,:) are not empty. */ int cum_nrow = 0; /* cumulative number of nonzero rows in L(:,k) */ int temp_nbrow; /* nonzero rows in current block L(i,k) */ lptr = lptr0; luptr = luptr0; int Lnbrow, Rnbrow; /* number of nonzero rows in look-ahead window, and remaining part. */ /******************************************************************* * Separating L blocks into the top part within look-ahead window * and the remaining ones. *******************************************************************/ int lookAheadBlk=0, RemainBlk=0; tt_start = SuperLU_timer_(); /* Sherry -- can this loop be threaded?? */ /* Loop through all blocks in L(:,k) to set up pointers to the start * of each block in the data arrays. * - lookAheadFullRow[i] := number of nonzero rows from block 0 to i * - lookAheadStRow[i] := number of nonzero rows before block i * - lookAhead_lptr[i] := point to the start of block i in L's index[] * - (ditto Remain_Info[i]) */ for (int i = 0; i < nlb; ++i) { ib = lsub[lptr]; /* Block number of L(i,k). */ temp_nbrow = lsub[lptr+1]; /* Number of full rows. */ int look_up_flag = 1; /* assume ib is outside look-up window */ for (int j = k0+1; j < SUPERLU_MIN (k0 + num_look_aheads+2, nsupers ); ++j) { if ( ib == perm_c_supno[j] ) { look_up_flag = 0; /* flag ib within look-up window */ break; /* Sherry -- can exit the loop?? */ } } if ( look_up_flag == 0 ) { /* ib is within look-up window */ if (lookAheadBlk==0) { lookAheadFullRow[lookAheadBlk] = temp_nbrow; } else { lookAheadFullRow[lookAheadBlk] = temp_nbrow + lookAheadFullRow[lookAheadBlk-1]; } lookAheadStRow[lookAheadBlk] = cum_nrow; lookAhead_lptr[lookAheadBlk] = lptr; lookAhead_ib[lookAheadBlk] = ib; lookAheadBlk++; } else { /* ib is not in look-up window */ if ( RemainBlk==0 ) { Remain_info[RemainBlk].FullRow = temp_nbrow; } else { Remain_info[RemainBlk].FullRow = temp_nbrow + Remain_info[RemainBlk-1].FullRow; } RemainStRow[RemainBlk] = cum_nrow; // Remain_lptr[RemainBlk] = lptr; Remain_info[RemainBlk].lptr = lptr; // Remain_ib[RemainBlk] = ib; Remain_info[RemainBlk].ib = ib; RemainBlk++; } cum_nrow += temp_nbrow; lptr += LB_DESCRIPTOR; /* Skip descriptor. */ lptr += temp_nbrow; /* Move to next block */ luptr += temp_nbrow; } /* for i ... set up pointers for all blocks in L(:,k) */ lptr = lptr0; luptr = luptr0; /* leading dimension of L look-ahead buffer, same as Lnbrow */ //int LDlookAhead_LBuff = lookAheadBlk==0 ? 0 :lookAheadFullRow[lookAheadBlk-1]; Lnbrow = lookAheadBlk==0 ? 0 : lookAheadFullRow[lookAheadBlk-1]; /* leading dimension of L remaining buffer, same as Rnbrow */ //int LDRemain_LBuff = RemainBlk==0 ? 0 : Remain_info[RemainBlk-1].FullRow; Rnbrow = RemainBlk==0 ? 0 : Remain_info[RemainBlk-1].FullRow; /* assert( cum_nrow == (LDlookAhead_LBuff + LDRemain_LBuff) );*/ /* Piyush fix */ //int LDlookAhead_LBuff = lookAheadBlk==0? 0 : lookAheadFullRow[lookAheadBlk-1]; nbrow = Lnbrow + Rnbrow; /* total number of rows in L */ LookAheadRowSepMOP += 2*knsupc*(nbrow); /*********************************************** * Gather U blocks (AFTER LOOK-AHEAD WINDOW) * ***********************************************/ tt_start = SuperLU_timer_(); if ( nbrow > 0 ) { /* L(:,k) is not empty */ /* * Counting U blocks */ ldu = 0; /* Calculate ldu for U(k,:) after look-ahead window. */ ncols = 0; /* Total number of nonzero columns in U(k,:) */ int temp_ncols = 0; /* jj0 contains the look-ahead window that was updated in dlook_ahead_update.c. Now the search can continue from that point, not to start from block 0. */ #if 0 // Sherry comment out 5/21/208 /* Save pointers at location right after look-ahead window for later restart. */ iukp0 = iukp; rukp0 = rukp; #endif /* if ( iam==0 ) printf("--- k0 %d, k %d, jj0 %d, nub %d\n", k0, k, jj0, nub);*/ /* * Loop through all blocks in U(k,:) to set up pointers to the start * of each block in the data arrays, store them in Ublock_info[j] * for block U(k,j). */ for (j = jj0; j < nub; ++j) { /* jj0 starts after look-ahead window. */ temp_ncols = 0; #if 1 /* Cannot remove following call, since perm_u != Identity */ arrive_at_ublock( j, &iukp, &rukp, &jb, &ljb, &nsupc, iukp0, rukp0, usub, perm_u, xsup, grid ); #else jb = usub[iukp]; /* ljb = LBj (jb, grid); Local block number of U(k,j). */ nsupc = SuperSize(jb); iukp += UB_DESCRIPTOR; /* Start fstnz of block U(k,j). */ #endif Ublock_info[j].iukp = iukp; Ublock_info[j].rukp = rukp; Ublock_info[j].jb = jb; /* if ( iam==0 ) printf("j %d: Ublock_info[j].iukp %d, Ublock_info[j].rukp %d," "Ublock_info[j].jb %d, nsupc %d\n", j, Ublock_info[j].iukp, Ublock_info[j].rukp, Ublock_info[j].jb, nsupc); */ /* Prepare to call GEMM. */ jj = iukp; for (; jj < iukp+nsupc; ++jj) { segsize = klst - usub[jj]; if ( segsize ) { ++temp_ncols; if ( segsize > ldu ) ldu = segsize; } } Ublock_info[j].full_u_cols = temp_ncols; ncols += temp_ncols; #if 0 // Sherry comment out 5/31/2018 */ /* Jump number of nonzeros in block U(k,jj); Move to block U(k,j+1) in nzval[] array. */ rukp += usub[iukp - 1]; iukp += nsupc; #endif } /* end for j ... compute ldu & ncols */ /* Now doing prefix sum on full_u_cols. * After this, full_u_cols is the number of nonzero columns * from block 0 to block j. */ for ( j = jj0+1; j < nub; ++j) { Ublock_info[j].full_u_cols += Ublock_info[j-1].full_u_cols; } /* Padding zeros to make {m,n,k} multiple of vector length. */ jj = 8; //n; if (gemm_padding > 0 && Rnbrow > jj && ncols > jj && ldu > jj) { gemm_m_pad = Rnbrow + (Rnbrow % GEMM_PADLEN); gemm_n_pad = ncols + (ncols % GEMM_PADLEN); //gemm_n_pad = ncols; //gemm_k_pad = ldu + (ldu % GEMM_PADLEN); gemm_k_pad = ldu; for (i = Rnbrow; i < gemm_m_pad; ++i) // padding A matrix for (j = 0; j < gemm_k_pad; ++j) Remain_L_buff[i + j*gemm_m_pad] = zero; for (i = 0; i < Rnbrow; ++i) for (j = ldu; j < gemm_k_pad; ++j) Remain_L_buff[i + j*gemm_m_pad] = zero; for (i = ldu; i < gemm_k_pad; ++i) // padding B matrix for (j = 0; j < gemm_n_pad; ++j) bigU[i + j*gemm_k_pad] = zero; for (i = 0; i < ldu; ++i) for (j = ncols; j < gemm_n_pad; ++j) bigU[i + j*gemm_k_pad] = zero; } else { gemm_m_pad = Rnbrow; gemm_n_pad = ncols; gemm_k_pad = ldu; } tempu = bigU; /* buffer the entire row block U(k,:) */ /* Gather U(k,:) into buffer bigU[] to prepare for GEMM */ #ifdef _OPENMP #pragma omp parallel for firstprivate(iukp, rukp) \ private(j,tempu, jb, nsupc,ljb,segsize, lead_zero, jj, i) \ default (shared) schedule(SCHEDULE_STRATEGY) #endif for (j = jj0; j < nub; ++j) { /* jj0 starts after look-ahead window. */ if (j==jj0) tempu = bigU; //else tempu = bigU + ldu * Ublock_info[j-1].full_u_cols; else tempu = bigU + gemm_k_pad * Ublock_info[j-1].full_u_cols; /* == processing each of the remaining columns in parallel == */ #if 0 /* Can remove following call, since search was already done. */ arrive_at_ublock(j, &iukp, &rukp, &jb, &ljb, &nsupc, iukp0, rukp0, usub,perm_u, xsup, grid); #else iukp = Ublock_info[j].iukp; rukp = Ublock_info[j].rukp; jb = Ublock_info[j].jb; nsupc = SuperSize (jb ); #endif /* Copy from U(k,j) to tempu[], padding zeros. */ for (jj = iukp; jj < iukp+nsupc; ++jj) { segsize = klst - usub[jj]; if ( segsize ) { lead_zero = ldu - segsize; for (i = 0; i < lead_zero; ++i) tempu[i] = zero; //tempu += lead_zero; #if (_OPENMP>=201307) #pragma omp simd #endif for (i = 0; i < segsize; ++i) tempu[i+lead_zero] = uval[rukp+i]; rukp += segsize; tempu += gemm_k_pad; } } } /* parallel for j = jj0 .. nub */ #if 0 if (ldu==0) printf("[%d] .. k0 %d, before updating: ldu %d, Lnbrow %d, Rnbrow %d, ncols %d\n",iam,k0,ldu,Lnbrow,Rnbrow, ncols); fflush(stdout); #endif GatherMOP += 2*ldu*ncols; } /* end if (nbrow>0), end gather U blocks */ GatherUTimer += SuperLU_timer_() - tt_start; int jj_cpu = nub; /* limit between CPU and GPU */ int thread_id; /*tempv = bigV;*/ /********************** * Gather L blocks * **********************/ tt_start = SuperLU_timer_(); /* Loop through the look-ahead blocks to copy Lval into the buffer */ #ifdef _OPENMP #pragma omp parallel for private(j,jj,tempu,tempv) default (shared) #endif for (i = 0; i < lookAheadBlk; ++i) { int StRowDest, temp_nbrow; if ( i==0 ) { StRowDest = 0; temp_nbrow = lookAheadFullRow[0]; } else { StRowDest = lookAheadFullRow[i-1]; temp_nbrow = lookAheadFullRow[i]-lookAheadFullRow[i-1]; } int StRowSource = lookAheadStRow[i]; /* Now copying one block into L lookahead buffer */ /* #pragma omp parallel for (gives slow down) */ // for (int j = 0; j < knsupc; ++j) { for (j = knsupc-ldu; j < knsupc; ++j) { /* skip leading columns corresponding to zero U rows */ #if 1 /* Better let compiler generate memcpy or vectorized code. */ //tempu = &lookAhead_L_buff[StRowDest + j*LDlookAhead_LBuff]; //tempu = &lookAhead_L_buff[StRowDest + j * Lnbrow]; tempu = &lookAhead_L_buff[StRowDest + (j - (knsupc-ldu)) * Lnbrow]; tempv = &lusup[luptr+j*nsupr + StRowSource]; #if (_OPENMP>=201307) #pragma omp simd #endif for (jj = 0; jj < temp_nbrow; ++jj) tempu[jj] = tempv[jj]; #else //memcpy(&lookAhead_L_buff[StRowDest + j*LDlookAhead_LBuff], memcpy(&lookAhead_L_buff[StRowDest + (j - (knsupc-ldu)) * Lnbrow], &lusup[luptr+j*nsupr + StRowSource], temp_nbrow * sizeof(doublecomplex) ); #endif } /* end for j ... */ } /* parallel for i ... gather Lval blocks from lookahead window */ /* Loop through the remaining blocks to copy Lval into the buffer */ #ifdef _OPENMP #pragma omp parallel for private(i,j,jj,tempu,tempv) default (shared) \ schedule(SCHEDULE_STRATEGY) #endif for (int i = 0; i < RemainBlk; ++i) { int StRowDest, temp_nbrow; if ( i==0 ) { StRowDest = 0; temp_nbrow = Remain_info[0].FullRow; } else { StRowDest = Remain_info[i-1].FullRow; temp_nbrow = Remain_info[i].FullRow - Remain_info[i-1].FullRow; } int StRowSource = RemainStRow[i]; /* Now copying a block into L remaining buffer */ // #pragma omp parallel for (gives slow down) // for (int j = 0; j < knsupc; ++j) { for (int j = knsupc-ldu; j < knsupc; ++j) { // printf("StRowDest %d Rnbrow %d StRowSource %d \n", StRowDest,Rnbrow ,StRowSource); #if 1 /* Better let compiler generate memcpy or vectorized code. */ //tempu = &Remain_L_buff[StRowDest + j*LDRemain_LBuff]; //tempu = &Remain_L_buff[StRowDest + (j - (knsupc-ldu)) * Rnbrow]; tempu = &Remain_L_buff[StRowDest + (j - (knsupc-ldu)) * gemm_m_pad]; tempv = &lusup[luptr + j*nsupr + StRowSource]; #if (_OPENMP>=201307) #pragma omp simd #endif for (jj = 0; jj < temp_nbrow; ++jj) tempu[jj] = tempv[jj]; #else //memcpy(&Remain_L_buff[StRowDest + j*LDRemain_LBuff], memcpy(&Remain_L_buff[StRowDest + (j - (knsupc-ldu)) * gemm_m_pad], &lusup[luptr+j*nsupr + StRowSource], temp_nbrow * sizeof(doublecomplex) ); #endif } /* end for j ... */ } /* parallel for i ... copy Lval into the remaining buffer */ tt_end = SuperLU_timer_(); GatherLTimer += tt_end - tt_start; /************************************************************************* * Perform GEMM (look-ahead L part, and remain L part) followed by Scatter *************************************************************************/ tempu = bigU; /* setting to the start of padded U(k,:) */ if ( Lnbrow>0 && ldu>0 && ncols>0 ) { /* Both L(:,k) and U(k,:) nonempty */ /*************************************************************** * Updating blocks in look-ahead window of the LU(look-ahead-rows,:) ***************************************************************/ /* Count flops for total GEMM calls */ ncols = Ublock_info[nub-1].full_u_cols; flops_t flps = 8.0 * (flops_t)Lnbrow * ldu * ncols; LookAheadScatterMOP += 3 * Lnbrow * ncols; /* scatter-add */ schur_flop_counter += flps; stat->ops[FACT] += flps; LookAheadGEMMFlOp += flps; #ifdef _OPENMP #pragma omp parallel default (shared) private(thread_id) { thread_id = omp_get_thread_num(); /* Ideally, should organize the loop as: for (j = 0; j < nub; ++j) { for (lb = 0; lb < lookAheadBlk; ++lb) { L(lb,k) X U(k,j) -> tempv[] } } But now, we use collapsed loop to achieve more parallelism. Total number of block updates is: (# of lookAheadBlk in L(:,k)) X (# of blocks in U(k,:)) */ int i = sizeof(int); int* indirect_thread = indirect + (ldt + CACHELINE/i) * thread_id; int* indirect2_thread = indirect2 + (ldt + CACHELINE/i) * thread_id; #pragma omp for \ private (nsupc,ljb,lptr,ib,temp_nbrow,cum_nrow) \ schedule(dynamic) #else /* not use _OPENMP */ thread_id = 0; int* indirect_thread = indirect; int* indirect2_thread = indirect2; #endif /* Each thread is assigned one loop index ij, responsible for block update L(lb,k) * U(k,j) -> tempv[]. */ for (int ij = 0; ij < lookAheadBlk*(nub-jj0); ++ij) { /* jj0 starts after look-ahead window. */ int j = ij/lookAheadBlk + jj0; int lb = ij%lookAheadBlk; /* Getting U block U(k,j) information */ /* unsigned long long ut_start, ut_end; */ int_t rukp = Ublock_info[j].rukp; int_t iukp = Ublock_info[j].iukp; int jb = Ublock_info[j].jb; int nsupc = SuperSize(jb); int ljb = LBj (jb, grid); /* destination column block */ int st_col; int ncols; /* Local variable counts only columns in the block */ if ( j > jj0 ) { /* jj0 starts after look-ahead window. */ ncols = Ublock_info[j].full_u_cols-Ublock_info[j-1].full_u_cols; st_col = Ublock_info[j-1].full_u_cols; } else { ncols = Ublock_info[j].full_u_cols; st_col = 0; } /* Getting L block L(i,k) information */ int_t lptr = lookAhead_lptr[lb]; int ib = lookAhead_ib[lb]; int temp_nbrow = lsub[lptr+1]; lptr += LB_DESCRIPTOR; int cum_nrow = (lb==0 ? 0 : lookAheadFullRow[lb-1]); /* Block-by-block GEMM in look-ahead window */ #if 0 i = sizeof(doublecomplex); doublecomplex* tempv1 = bigV + thread_id * (ldt*ldt + CACHELINE/i); #else doublecomplex* tempv1 = bigV + thread_id * (ldt*ldt); #endif #if ( PRNTlevel>= 1) if (thread_id == 0) tt_start = SuperLU_timer_(); gemm_max_m = SUPERLU_MAX(gemm_max_m, temp_nbrow); gemm_max_n = SUPERLU_MAX(gemm_max_n, ncols); gemm_max_k = SUPERLU_MAX(gemm_max_k, ldu); #endif #if defined (USE_VENDOR_BLAS) zgemm_("N", "N", &temp_nbrow, &ncols, &ldu, &alpha, //&lookAhead_L_buff[(knsupc-ldu)*Lnbrow+cum_nrow], &Lnbrow, &lookAhead_L_buff[cum_nrow], &Lnbrow, &tempu[st_col*ldu], &ldu, &beta, tempv1, &temp_nbrow, 1, 1); #else zgemm_("N", "N", &temp_nbrow, &ncols, &ldu, &alpha, //&lookAhead_L_buff[(knsupc-ldu)*Lnbrow+cum_nrow], &Lnbrow, &lookAhead_L_buff[cum_nrow], &Lnbrow, &tempu[st_col*ldu], &ldu, &beta, tempv1, &temp_nbrow); #endif #if (PRNTlevel>=1 ) if (thread_id == 0) { tt_end = SuperLU_timer_(); LookAheadGEMMTimer += tt_end - tt_start; tt_start = tt_end; } #endif if ( ib < jb ) { zscatter_u ( ib, jb, nsupc, iukp, xsup, klst, temp_nbrow, lptr, temp_nbrow, lsub, usub, tempv1, Ufstnz_br_ptr, Unzval_br_ptr, grid ); } else { #if 0 //#ifdef USE_VTUNE __SSC_MARK(0x111);// start SDE tracing, note uses 2 underscores __itt_resume(); // start VTune, again use 2 underscores #endif zscatter_l ( ib, ljb, nsupc, iukp, xsup, klst, temp_nbrow, lptr, temp_nbrow, usub, lsub, tempv1, indirect_thread, indirect2_thread, Lrowind_bc_ptr, Lnzval_bc_ptr, grid ); #if 0 //#ifdef USE_VTUNE __itt_pause(); // stop VTune __SSC_MARK(0x222); // stop SDE tracing #endif } #if ( PRNTlevel>=1 ) if (thread_id == 0) LookAheadScatterTimer += SuperLU_timer_() - tt_start; #endif } /* end omp for ij = ... */ #ifdef _OPENMP } /* end omp parallel */ #endif } /* end if Lnbrow>0 ... look-ahead GEMM and scatter */ /*************************************************************** * Updating remaining rows and columns on CPU. ***************************************************************/ ncols = jj_cpu==0 ? 0 : Ublock_info[jj_cpu-1].full_u_cols; if ( Rnbrow>0 && ldu>0 ) { /* There are still blocks remaining ... */ double flps = 8.0 * (double)Rnbrow * ldu * ncols; schur_flop_counter += flps; stat->ops[FACT] += flps; #if ( PRNTlevel>=1 ) RemainGEMM_flops += flps; gemm_max_m = SUPERLU_MAX(gemm_max_m, Rnbrow); gemm_max_n = SUPERLU_MAX(gemm_max_n, ncols); gemm_max_k = SUPERLU_MAX(gemm_max_k, ldu); tt_start = SuperLU_timer_(); /* printf("[%d] .. k0 %d, before large GEMM: %d-%d-%d, RemainBlk %d\n", iam, k0,Rnbrow,ldu,ncols,RemainBlk); fflush(stdout); assert( Rnbrow*ncols < bigv_size ); */ #endif /* calling aggregated large GEMM, result stored in bigV[]. */ #if defined (USE_VENDOR_BLAS) //zgemm_("N", "N", &Rnbrow, &ncols, &ldu, &alpha, zgemm_("N", "N", &gemm_m_pad, &gemm_n_pad, &gemm_k_pad, &alpha, //&Remain_L_buff[(knsupc-ldu)*Rnbrow], &Rnbrow, &Remain_L_buff[0], &gemm_m_pad, &bigU[0], &gemm_k_pad, &beta, bigV, &gemm_m_pad, 1, 1); #else //zgemm_("N", "N", &Rnbrow, &ncols, &ldu, &alpha, zgemm_("N", "N", &gemm_m_pad, &gemm_n_pad, &gemm_k_pad, &alpha, //&Remain_L_buff[(knsupc-ldu)*Rnbrow], &Rnbrow, &Remain_L_buff[0], &gemm_m_pad, &bigU[0], &gemm_k_pad, &beta, bigV, &gemm_m_pad); #endif #if ( PRNTlevel>=1 ) tt_end = SuperLU_timer_(); RemainGEMMTimer += tt_end - tt_start; #if ( PROFlevel>=1 ) //fprintf(fgemm, "%8d%8d%8d %16.8e\n", Rnbrow, ncols, ldu, // (tt_end - tt_start)*1e6); // time in microsecond //fflush(fgemm); gemm_stats[gemm_count].m = Rnbrow; gemm_stats[gemm_count].n = ncols; gemm_stats[gemm_count].k = ldu; gemm_stats[gemm_count++].microseconds = (tt_end - tt_start) * 1e6; #endif tt_start = SuperLU_timer_(); #endif #ifdef USE_VTUNE __SSC_MARK(0x111);// start SDE tracing, note uses 2 underscores __itt_resume(); // start VTune, again use 2 underscores #endif /* Scatter into destination block-by-block. */ #ifdef _OPENMP #pragma omp parallel default(shared) private(thread_id) { thread_id = omp_get_thread_num(); /* Ideally, should organize the loop as: for (j = 0; j < jj_cpu; ++j) { for (lb = 0; lb < RemainBlk; ++lb) { L(lb,k) X U(k,j) -> tempv[] } } But now, we use collapsed loop to achieve more parallelism. Total number of block updates is: (# of RemainBlk in L(:,k)) X (# of blocks in U(k,:)) */ int i = sizeof(int); int* indirect_thread = indirect + (ldt + CACHELINE/i) * thread_id; int* indirect2_thread = indirect2 + (ldt + CACHELINE/i) * thread_id; #pragma omp for \ private (j,lb,rukp,iukp,jb,nsupc,ljb,lptr,ib,temp_nbrow,cum_nrow) \ schedule(dynamic) #else /* not use _OPENMP */ thread_id = 0; int* indirect_thread = indirect; int* indirect2_thread = indirect2; #endif /* Each thread is assigned one loop index ij, responsible for block update L(lb,k) * U(k,j) -> tempv[]. */ for (int ij = 0; ij < RemainBlk*(jj_cpu-jj0); ++ij) { /* jj_cpu := nub, jj0 starts after look-ahead window. */ int j = ij / RemainBlk + jj0; /* j-th block in U panel */ int lb = ij % RemainBlk; /* lb-th block in L panel */ /* Getting U block U(k,j) information */ /* unsigned long long ut_start, ut_end; */ int_t rukp = Ublock_info[j].rukp; int_t iukp = Ublock_info[j].iukp; int jb = Ublock_info[j].jb; int nsupc = SuperSize(jb); int ljb = LBj (jb, grid); int st_col; int ncols; if ( j>jj0 ) { ncols = Ublock_info[j].full_u_cols - Ublock_info[j-1].full_u_cols; st_col = Ublock_info[j-1].full_u_cols; } else { ncols = Ublock_info[j].full_u_cols; st_col = 0; } /* Getting L block L(i,k) information */ int_t lptr = Remain_info[lb].lptr; int ib = Remain_info[lb].ib; int temp_nbrow = lsub[lptr+1]; lptr += LB_DESCRIPTOR; int cum_nrow = (lb==0 ? 0 : Remain_info[lb-1].FullRow); /* tempv1 points to block(i,j) in bigV : LDA == Rnbrow */ //double* tempv1 = bigV + (st_col * Rnbrow + cum_nrow); Sherry doublecomplex* tempv1 = bigV + (st_col * gemm_m_pad + cum_nrow); /* Sherry */ // printf("[%d] .. before scatter: ib %d, jb %d, temp_nbrow %d, Rnbrow %d\n", iam, ib, jb, temp_nbrow, Rnbrow); fflush(stdout); /* Now scattering the block */ if ( ib < jb ) { zscatter_u ( ib, jb, nsupc, iukp, xsup, //klst, Rnbrow, /*** klst, temp_nbrow, Sherry */ klst, gemm_m_pad, /*** klst, temp_nbrow, Sherry */ lptr, temp_nbrow, /* row dimension of the block */ lsub, usub, tempv1, Ufstnz_br_ptr, Unzval_br_ptr, grid ); } else { zscatter_l( ib, ljb, nsupc, iukp, xsup, //klst, temp_nbrow, Sherry klst, gemm_m_pad, /*** temp_nbrow, Sherry */ lptr, temp_nbrow, /* row dimension of the block */ usub, lsub, tempv1, indirect_thread, indirect2_thread, Lrowind_bc_ptr,Lnzval_bc_ptr, grid ); } } /* end omp for (int ij =...) */ #ifdef _OPENMP } /* end omp parallel region */ #endif #if ( PRNTlevel>=1 ) RemainScatterTimer += SuperLU_timer_() - tt_start; #endif #ifdef USE_VTUNE __itt_pause(); // stop VTune __SSC_MARK(0x222); // stop SDE tracing #endif } /* end if Rnbrow>0 ... update remaining block */ } /* end if L(:,k) and U(k,:) are not empty */
ompfor7.c
/* * test #define * Liao 12/1/2010 */ #include <stdio.h> #ifdef _OPENMP #include <omp.h> #endif #define P 4 void foo(int iend, int ist) { int i=0; i= i+P; #pragma omp parallel { #pragma omp single printf ("Using %d threads.\n",omp_get_num_threads()); #pragma omp for nowait schedule(static,P) for (i=iend;i>=ist;i--) { printf("Iteration %d is carried out by thread %d\n",i, omp_get_thread_num()); } } }
estimator.h
// Copyright (C) 2013 The Regents of the University of California (Regents). // 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 Regents or University of California 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 HOLDERS 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. // // Please contact the author of this library if you have any questions. // Author: Chris Sweeney (cmsweeney@cs.ucsb.edu) #ifndef THEIA_SOLVERS_ESTIMATOR_H_ #define THEIA_SOLVERS_ESTIMATOR_H_ #include <glog/logging.h> #ifdef THEIA_USE_OPENMP #include <omp.h> #endif #include <vector> namespace theia { // Templated class for estimating a model for RANSAC. This class is purely a // virtual class and should be implemented for the specific task that RANSAC is // being used for. Two methods must be implemented: EstimateModel and Error. All // other methods are optional, but will likely enhance the quality of the RANSAC // output. // // NOTE: RANSAC, ARRSAC, and other solvers work best if Datum and Model are // lightweight classes or structs. template <typename DatumType, typename ModelType> class Estimator { public: typedef DatumType Datum; typedef ModelType Model; Estimator() {} virtual ~Estimator() {} // Get the minimum number of samples needed to generate a model. virtual double SampleSize() const = 0; // Given a set of data points, estimate the model. Users should implement this // function appropriately for the task being solved. Returns true for // successful model estimation (and outputs model), false for failed // estimation. Typically, this is a minimal set, but it is not required to be. virtual bool EstimateModel(const std::vector<Datum>& data, std::vector<Model>* model) const = 0; // Estimate a model from a non-minimal sampling of the data. E.g. for a line, // use SVD on a set of points instead of constructing a line from two points. // By default, this simply implements the minimal case. virtual bool EstimateModelNonminimal(const std::vector<Datum>& data, std::vector<Model>* model) const { return EstimateModel(data, model); } // Refine the model based on an updated subset of data, and a pre-computed // model. Can be optionally implemented. virtual bool RefineModel(const std::vector<Datum>& data, Model* model) const { return true; } // Given a model and a data point, calculate the error. Users should implement // this function appropriately for the task being solved. virtual double Error(const Datum& data, const Model& model) const = 0; // Compute the residuals of many data points. By default this is just a loop // that calls Error() on each data point, but this function can be useful if // the errors of multiple points may be estimated simultanesously (e.g., // matrix multiplication to compute the reprojection error of many points at // once). virtual std::vector<double> Residuals(const std::vector<Datum>& data, const Model& model) const { std::vector<double> residuals(data.size()); #pragma omp parallel for for (int i = 0; i < data.size(); i++) { residuals[i] = Error(data[i], model); } return residuals; } // Returns the set inliers of the data set based on the error threshold // provided. std::vector<int> GetInliers(const std::vector<Datum>& data, const Model& model, double error_threshold) const { std::vector<int> inliers; inliers.reserve(data.size()); for (int i = 0; i < data.size(); i++) { if (Error(data[i], model) < error_threshold) { inliers.push_back(i); } } return inliers; } // Enable a quick check to see if the model is valid. This can be a geometric // check or some other verification of the model structure. virtual bool ValidModel(const Model& model) const { return true; } }; } // namespace theia #endif // THEIA_SOLVERS_ESTIMATOR_H_
resize-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * \file resize-inl.h * \brief image resize operator using opencv and only support bilinear resize * \author Jake Lee */ #ifndef MXNET_OPERATOR_IMAGE_RESIZE_INL_H_ #define MXNET_OPERATOR_IMAGE_RESIZE_INL_H_ #include <mxnet/base.h> #include <vector> #include "../mxnet_op.h" #include "../operator_common.h" #include "image_utils.h" #if MXNET_USE_OPENCV #include <opencv2/opencv.hpp> #endif // MXNET_USE_OPENCV namespace mxnet { namespace op { namespace image { using namespace mshadow; #if MXNET_USE_CUDA template<typename DType, typename T, typename Acctype> void ResizeImplCUDA(Stream<gpu> *s, const T input, const T output); #endif // MXNET_USE_CUDA struct ResizeParam : public dmlc::Parameter<ResizeParam> { nnvm::Tuple<int> size; bool keep_ratio; int interp; DMLC_DECLARE_PARAMETER(ResizeParam) { DMLC_DECLARE_FIELD(size) .set_default(nnvm::Tuple<int>()) .describe("Size of new image. Could be (width, height) or (size)"); DMLC_DECLARE_FIELD(keep_ratio) .describe("Whether to resize the short edge or both edges to `size`, " "if size is give as an integer.") .set_default(false); DMLC_DECLARE_FIELD(interp) .set_default(1) .describe("Interpolation method for resizing. By default uses bilinear interpolation" "Options are INTER_NEAREST - a nearest-neighbor interpolation" "INTER_LINEAR - a bilinear interpolation" "INTER_AREA - resampling using pixel area relation" "INTER_CUBIC - a bicubic interpolation over 4x4 pixel neighborhood" "INTER_LANCZOS4 - a Lanczos interpolation over 8x8 pixel neighborhood" "Note that the GPU version only support bilinear interpolation(1)" " and the result on cpu would be slightly different from gpu." "It uses opencv resize function which tend to align center on cpu" "while using contrib.bilinearResize2D which aligns corner on gpu"); } }; // handle the keep ratio param inline SizeParam GetHeightAndWidth(int data_h, int data_w, const ResizeParam& param) { CHECK((param.size.ndim() == 1) || (param.size.ndim() == 2)) << "Input size dimension must be 1 or 2, but got " << param.size.ndim(); int resized_h; int resized_w; if (param.size.ndim() == 1) { CHECK_GT(param.size[0], 0) << "Input size should be greater than 0, but got " << param.size[0]; if (!param.keep_ratio) { resized_h = param.size[0]; resized_w = param.size[0]; } else { if (data_h > data_w) { resized_w = param.size[0]; resized_h = static_cast<int>(data_h * resized_w / data_w); } else { resized_h = param.size[0]; resized_w = static_cast<int>(data_w * resized_h / data_h); } } } else { CHECK_GT(param.size[0], 0) << "Input width should be greater than 0, but got " << param.size[0]; CHECK_GT(param.size[1], 0) << "Input height should be greater than 0, but got " << param.size[1]; resized_h = param.size[1]; resized_w = param.size[0]; } return SizeParam(resized_h, resized_w); } inline bool ResizeShape(const nnvm::NodeAttrs& attrs, std::vector<TShape> *in_attrs, std::vector<TShape> *out_attrs) { // input attrs should only be (h, w, c) or (n, h, w, c) CHECK((in_attrs->at(0).ndim() == 3U) || (in_attrs->at(0).ndim() == 4U)) << "Input image dimension should be 3 or 4 but got " << in_attrs->at(0).ndim(); const auto& ishape = (*in_attrs)[0]; const ResizeParam& param = nnvm::get<ResizeParam>(attrs.parsed); SizeParam size; if (ishape.ndim() == 3) { size = GetHeightAndWidth(ishape[H], ishape[W], param); SHAPE_ASSIGN_CHECK(*out_attrs, 0, TShape({size.height, size.width, ishape[C]})); } else { size = GetHeightAndWidth(ishape[kH], ishape[kW], param); SHAPE_ASSIGN_CHECK(*out_attrs, 0, TShape({ishape[N], size.height, size.width, ishape[kC]})); } return true; } inline void ResizeImpl(const std::vector<TBlob> &inputs, const std::vector<TBlob> &outputs, const int height, const int width, const int interp, const int input_index = 0, const int output_index = 0) { #if MXNET_USE_OPENCV CHECK_NE(inputs[0].type_flag_, mshadow::kFloat16) << "opencv image mat doesn't support fp16"; CHECK((inputs[0].type_flag_ != mshadow::kInt32) || (inputs[0].type_flag_ != mshadow::kInt64)) << "opencv resize doesn't support int32, int64"; // mapping to opencv matrix element type according to channel const int DTYPE[] = {CV_32F, CV_64F, -1, CV_8U, CV_32S}; if (inputs[0].ndim() == 3) { const int cv_type = CV_MAKETYPE(DTYPE[inputs[0].type_flag_], inputs[0].shape_[C]); cv::Mat buf(inputs[0].shape_[H], inputs[0].shape_[W], cv_type, inputs[0].dptr_); cv::Mat dst(outputs[0].shape_[H], outputs[0].shape_[W], cv_type, outputs[0].dptr_); cv::resize(buf, dst, cv::Size(width, height), 0, 0, interp); CHECK(!dst.empty()); CHECK_EQ(static_cast<void*>(dst.ptr()), outputs[0].dptr_); } else { const int cv_type = CV_MAKETYPE(DTYPE[inputs[0].type_flag_], inputs[0].shape_[kC]); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { cv::Mat buf(inputs[0].shape_[kH], inputs[0].shape_[kW], cv_type, inputs[0].dptr<DType>() + input_index); cv::Mat dst(outputs[0].shape_[kH], outputs[0].shape_[kW], cv_type, outputs[0].dptr<DType>() + output_index); cv::resize(buf, dst, cv::Size(width, height), 0, 0, interp); CHECK(!dst.empty()); CHECK_EQ(static_cast<void*>(dst.ptr()), outputs[0].dptr<DType>() + output_index); }); } #else LOG(FATAL) << "Build with USE_OPENCV=1 for image resize operator."; #endif // MXNET_USE_OPENCV } template <typename xpu> inline void Resize(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { CHECK_EQ(outputs.size(), 1U); const ResizeParam& param = nnvm::get<ResizeParam>(attrs.parsed); SizeParam size; if (std::is_same<xpu, gpu>::value) { #if MXNET_USE_CUDA CHECK(param.interp == 1) << "interp should be 1 for using Resize on GPU."; mshadow::Stream<gpu> *s = ctx.get_stream<gpu>(); MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { if (inputs[0].ndim() == 3) { Tensor<gpu, 3, DType> input = inputs[0].get<gpu, 3, DType>(s); Tensor<gpu, 3, DType> output = outputs[0].get<gpu, 3, DType>(s); ResizeImplCUDA<DType, Tensor<gpu, 3, DType>, float>(s, input, output); } else { Tensor<gpu, 4, DType> input = inputs[0].get<gpu, 4, DType>(s); Tensor<gpu, 4, DType> output = outputs[0].get<gpu, 4, DType>(s); ResizeImplCUDA<DType, Tensor<gpu, 4, DType>, float>(s, input, output); } }); #endif // MXNET_USE_CUDA } else if (inputs[0].ndim() == 3) { size = GetHeightAndWidth(inputs[0].shape_[H], inputs[0].shape_[W], param); ResizeImpl(inputs, outputs, size.height, size.width, param.interp); } else { size = GetHeightAndWidth(inputs[0].shape_[kH], inputs[0].shape_[kW], param); const auto batch_size = inputs[0].shape_[N]; const auto input_step = inputs[0].shape_[kH] * inputs[0].shape_[kW] * inputs[0].shape_[kC]; const auto output_step = size.height * size.width * inputs[0].shape_[kC]; #pragma omp parallel for for (auto i = 0; i < batch_size; ++i) { ResizeImpl(inputs, outputs, size.height, size.width, param.interp, i * input_step, i * output_step); } } } } // namespace image } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_IMAGE_RESIZE_INL_H_
quick_fermi_dirac.c
/* A. Odrzywolek, andrzej.odrzywolek@uj.edu.pl, 01-06-2020 */ #include "../fermidirac.h" #include <stdlib.h> #include <string.h> #include <unistd.h> #include <math.h> #include <stdio.h> #include <float.h> /* SECTION FOR FAST VERSIONS */ void fixedFfermi_derivatives(const double k, const double eta, const double theta, const double h, double hMIN, double hMAX, double * F, double *dF_deta, double *d2F_deta2, double * dF_dtheta, double *d2F_dtheta2, double *d2F_dtheta_deta) { int ii,num; double t, x, dx, f, integral=0.0, integral_deta=0.0, integral_deta2=0.0, integral_dtheta=0.0, integral_dtheta2=0.0, integral_deta_dtheta=0.0; double xst,dxst,factor, denom, denomi; //AUX vars similar to used by FXT code num = (int) -hMIN/h; hMIN = -num*h; num = (int) hMAX/h; hMAX = num*h; #if DEBUG printf("fixedFfermi: %d %lf %lf\n", num, hMIN,hMAX); #endif num = (int) (hMAX-hMIN)/h; for(ii=0;ii<=num;ii++) { t = hMIN + ii*h; //t = hMAX - ii*h; x = exp(t-exp(-t)); dx = 1.0 +exp(-t); // This is NOT D[x,t], D[x,t] = x*dx ! xst = 1.0+ 0.5*theta*x; dxst = sqrt(xst); factor = exp(x-eta); denom = 1.0+factor; denomi = 1.0/denom; f = 1.0/(1.0+factor)*exp( (k+1.0) * (t - exp(-t)) )*dxst * dx; integral += f; integral_deta += f*factor*denomi; integral_deta2 += f*factor*denomi*denomi*(factor-1.0); integral_dtheta += f*0.25*x/xst; integral_dtheta2 += -f*0.25*x/xst*x/xst*0.25; integral_deta_dtheta += f*0.25*x/xst*factor*denomi; } *F = h*integral; *dF_deta = h*integral_deta; *d2F_deta2 = h*integral_deta2; *dF_dtheta = h*integral_dtheta; *d2F_dtheta2 = h*integral_dtheta2; *d2F_dtheta_deta = h*integral_deta_dtheta; } void fixedFfermi_derivatives_v2(const double k, const double eta, const double theta, const double h, double hMIN, double hMAX, double * F, double *dF_deta, double *d2F_deta2, double * dF_dtheta, double *d2F_dtheta2, double *d2F_dtheta_deta, double * d3F_dtheta3, double *d3F_dtheta2_deta, double *d3F_dtheta_deta2, double *d3F_deta3, int D_MAX) { int ii,num; double t, x, dx, f, integral=0.0, integral_deta=0.0, integral_deta2=0.0, integral_dtheta=0.0, integral_dtheta2=0.0, integral_deta_dtheta=0.0, integral_dtheta3=0.0, integral_dtheta2_deta=0.0, integral_dtheta_deta2=0.0, integral_deta3=0.0; double g2,g,factor, denom, s; //AUX vars similar to used by FXT code num = (int) -hMIN/h; hMIN = -num*h; num = (int) hMAX/h; hMAX = num*h; #if DEBUG printf("fixedFfermi: %d %lf %lf\n", num, hMIN,hMAX); #endif num = (int) (hMAX-hMIN)/h; for(ii=0;ii<=num;ii++) { t = hMIN + ii*h; //t = hMAX - ii*h; x = exp(t-exp(-t)); dx = 1.0 +exp(-t); // This is NOT D[x,t], D[x,t] = x*dx ! g2 = 1.0+ 0.5*theta*x; g = sqrt(g2); factor = exp(x-eta); denom = 1.0+factor; s = 1.0/denom; f = 1.0/(1.0+factor)*exp( (k+1.0) * (t - exp(-t)) )*g*dx; //A lot of optimalization possible below, blocked by if() construct integral += f; if(D_MAX>0) integral_deta += f*factor*s; if(D_MAX>0) integral_dtheta += f*0.25*x/g2; if(D_MAX>1) integral_deta2 += f*factor*s*s*(factor-1.0); if(D_MAX>1) integral_dtheta2 += -f*0.25*x/g2*x/g2*0.25; if(D_MAX>1) integral_deta_dtheta += f*0.25*x/g2*factor*s; if(D_MAX>2) integral_dtheta3 += (f*0.25*x/g2*x/g2*0.25)*0.75*x/g2; if(D_MAX>2) integral_dtheta2_deta += (-f*0.25*x/g2*x/g2*0.25)*factor*s; if(D_MAX>2) integral_dtheta_deta2 += (f*factor*s*s*(factor-1.0))*x/4.0/g2; if(D_MAX>2) integral_deta3 += f*(1.0-7.0*s+12.0*s*s-6.0*s*s*s); //NOT YET implemented; 3-rd derivatives UNTESTED } *F = h*integral; *dF_deta = h*integral_deta; *d2F_deta2 = h*integral_deta2; *dF_dtheta = h*integral_dtheta; *d2F_dtheta2 = h*integral_dtheta2; *d2F_dtheta_deta = h*integral_deta_dtheta; *d3F_dtheta3 = h*integral_dtheta3; *d3F_dtheta2_deta = h*integral_dtheta2_deta; *d3F_dtheta_deta2 = h*integral_dtheta_deta2; *d3F_deta3 = h*integral_deta3; } void fixedFfermi_derivatives_v3(const double k, const double eta, const double theta, const double h, double hMIN, double hMAX, double * F, double *dF_deta, double *d2F_deta2, double * dF_dtheta, double *d2F_dtheta2, double *d2F_dtheta_deta, double * d3F_dtheta3, double *d3F_dtheta2_deta, double *d3F_dtheta_deta2, double *d3F_deta3) { int ii,num; double t, x, dx, f, integral=0.0, integral_deta=0.0, integral_deta2=0.0, integral_dtheta=0.0, integral_dtheta2=0.0, integral_deta_dtheta=0.0; double integral_dtheta3=0.0, integral_dtheta2_deta=0.0, integral_dtheta_deta2=0.0, integral_deta3=0.0; double s,g,g2,z; //AUX vars num = (int) -hMIN/h; hMIN = -num*h; num = (int) hMAX/h; hMAX = num*h; num = (int) (hMAX-hMIN)/h; for(ii=0;ii<=num;ii++) { t = hMIN + ii*h; //t = hMAX - ii*h; x = exp(t-exp(-t)); dx = 1.0 +exp(-t); // This is NOT D[x,t], D[x,t] = x*dx ! g2 = 1.0+ 0.5*theta*x; g = sqrt(g2); s = sigmoid(eta-x); f = s*exp( (k+1.0)*(t - exp(-t)) )*g*dx; z = 0.25*x/g2; /* s1 = s*(1-s); s2 = s1*(1-2.0*s); s3 = s1*(1-6.0*s1); */ integral += f; integral_deta += f*(1.0-s); integral_deta2 += f*(1.0-s)*(1.0-2.0*s); //integral_deta2 += f*(1.0+s*(2.0*s-3.0)); //WHY THIS PRODUCES 10x more error than the rest? A.O. 2021-10-30 integral_dtheta += f*z; integral_dtheta2 += -f*z*z; integral_deta_dtheta += f*z*(1.0-s); integral_dtheta3 += 3.0*f*z*z*z; integral_dtheta2_deta += -f*z*z*(1.0-s); integral_dtheta_deta2 += f*z*(1.0+s*(2.0*s-3.0)); integral_deta3 += f*(1.0 + s*(-7.0 + (12.0 - 6.0*s)*s)); } *F = h*integral; *dF_deta = h*integral_deta; *d2F_deta2 = h*integral_deta2; *dF_dtheta = h*integral_dtheta; *d2F_dtheta2 = h*integral_dtheta2; *d2F_dtheta_deta = h*integral_deta_dtheta; *d3F_dtheta3 = h*integral_dtheta3; *d3F_dtheta2_deta = h*integral_dtheta2_deta; *d3F_dtheta_deta2 = h*integral_dtheta_deta2; *d3F_deta3 = h*integral_deta3; } double fixedFfermi(const double k, const double eta, const double theta, const double h, double hMIN, double hMAX) { int ii,num; double t, x, dx, integral=0.0; double c=0.0,tmp,y; // https://en.wikipedia.org/wiki/Kahan_summation_algorithm num = (int) -hMIN/h; hMIN = -num*h; num = (int) hMAX/h; hMAX = num*h; #if DEBUG printf("fixedFfermi: %d %lf %lf\n", num, hMIN,hMAX); #endif num = (int) (hMAX-hMIN)/h; // #pragma omp simd // #pragma ivdep for(ii=0;ii<=num;ii++) { t = hMIN + ii*h; //t = hMAX - ii*h; x = exp(t-exp(-t)); dx = 1.0 +exp(-t); integral+= 1.0/(1.0+exp(x)*exp(-eta) )*exp( (k+1.0) * (t - exp(-t)) )*sqrt(1.0+ 0.5*theta*x) * dx; //integral+= 1.0/(1.0+exp(x-eta) )*pow(x,k+1.0)*sqrt(1.0+ 0.5*theta*x) * dx; /* x = exp(t-exp(-t)); dx = 1.0 +exp(-t); y = 1.0/(1.0+exp(x)*exp(-eta) ) *exp( (k+1.0) * (t - exp(-t)) ) *sqrt(1.0+ 0.5*theta*x) * dx - c; tmp = integral + y; c = (tmp-integral) - y; integral=tmp; */ } return h*integral; } long double fixedFfermi_long(const long double k, const long double eta, const long double theta, const long double h, const long double hMIN, const long double hMAX) { int ii,num; long double t, x, dx, integral=0.0L; long double h_MIN,h_MAX; num = (int) -hMIN/h; h_MIN = -num*h; num = (int) hMAX/h; h_MAX = num*h; num = (int) (h_MAX-h_MIN)/h; #pragma omp simd #pragma ivdep for(ii=0;ii<=num;ii++) { t = h_MIN + ii*h; //t = h_MAX - ii*h; x = expl(t-expl(-t)); dx = 1.0L +expl(-t); integral+= 1.0L/(1.0L+expl(x)*expl(-eta) ) *expl( (k+1.0L) * (t - expl(-t)) ) *sqrtl(1.0L+ 0.5L*theta*x) * dx; } return h*integral; } float fixedFfermif(const float k, const float eta, const float theta, const float h, float hMIN, float hMAX) { int ii,num; float t, x, dx, fd, integral=0.0f; num = (int) -hMIN/h; hMIN = -num*h; num = (int) hMAX/h; hMAX = num*h; num = (int) (hMAX-hMIN)/h; #pragma omp simd #pragma ivdep for(ii=0;ii<=num;ii++) { t = hMIN + ii*h; if( (eta>k) && (k>0) ) x = eta*expf(t-expf(-t)); else x = expf(t-expf(-t)); dx = 1.0f +expf(-t); fd = 1.0f/(1.0f+expf(x-eta) ); integral+= fd*powf(x,k+1)*sqrtf(1.0f+ 0.5f*theta*x)*dx; } return h*integral; } double gaussFfermi(const double k, const double eta, const double theta) { const double xg_leg[4] = {0.18343464249564980493947614236018398066675781291297378231718847369920\ 44742215421141160682237111233537, \ 0.52553240991632898581773904918924634904196424312039285775085709927245\ 48207685612725239614001936319821, \ 0.79666647741362673959155393647583043683717173161596483207017029503921\ 73056764730921471519272957259390, \ 0.96028985649753623168356086856947299042823523430145203827163977737242\ 48977434192844394389592633122683 }; const double wg_leg[4] = {0.36268378337836198296515044927719561219414603989433054052482306756668\ 67347239066773243660420848285096, \ 0.31370664587788728733796220198660131326032899900273493769026394507495\ 62719421734969616980762339285560, \ 0.22238103445337447054435599442624088443013087005124956472590928929361\ 6814570449040853653142377197928, \ 0.10122853629037625915253135430996219011539409105168495705900369806474\ 0178763470784860282739304045007}; const int num=4; const double d = 3.3609e0 ; const double sg = 9.1186e-2 ; const double a1 = 6.7774e0 ; const double b1 = 1.1418e0 ; const double c1 = 2.9826e0 ; const double a2 = 3.7601e0 ; const double b2 = 9.3719e-2 ; const double c2 = 2.1063e-2 ; const double d2 = 3.1084e1 ; const double e2 = 1.0056e0 ; const double a3 = 7.5669e0 ; const double b3 = 1.1695e0 ; const double c3 = 7.5416e-1 ; const double d3 = 6.6558e0 ; const double e3 =-1.2819e-1 ; double x1,x2,x3,s1,s2,s3,s12,xi,xi2,eta1; double fd, res1,res2,res3,res4; // definition of xi: eta1=sg*(eta-d); if (eta1<50.0) xi=log(1.0+exp(eta1))/sg; else xi=eta-d; xi2=xi*xi; // definition of the x_i: x1=(a1 +b1*xi+c1* xi2)/(1.0+c1*xi); x2=(a2 +b2*xi+c2*d2*xi2)/(1.0+e2*xi+c2* xi2); x3=(a3 +b3*xi+c3*d3*xi2)/(1.0+e3*xi+c3* xi2); // breakpoints: s1=x1-x2; s2=x1; s3=x1+x3; s12=sqrt(s1); //first integral of four: int_0^Sqrt[s1] f(x^2) 2x dx double center, hlfrun, result, x, z, f, a, b; int i; a=0.0; b=s12; center = 0.5* (a+b); hlfrun = 0.5* (b-a); result = 0.0; #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center + hlfrun*xg_leg[i]; z = x*x; f = pow(z,k)*sqrt(1.0+0.5*z*theta)/(1.0+exp(z-eta))*2.0*x; result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center - hlfrun*xg_leg[i]; z = x*x; f = pow(z,k)*sqrt(1.0+0.5*z*theta)/(1.0+exp(z-eta))*2.0*x; result += f*wg_leg[i]; } res1 = result * hlfrun; //integral 2 of 4: int_s1^s3 f(x) dx a=s1; b=s2; center = 0.5* (a+b); hlfrun = 0.5* (b-a); result = 0.0; #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center + hlfrun*xg_leg[i]; f = pow(x,k)*sqrt(1.0+0.5*x*theta)/(1.0+exp(x-eta)); result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center - hlfrun*xg_leg[i]; f = pow(x,k)*sqrt(1.0+0.5*x*theta)/(1.0+exp(x-eta)); result += f*wg_leg[i]; } res2 = result * hlfrun; //integral 3 of 4: int_s2^s3 f(x) dx a=s2; b=s3; center = 0.5* (a+b); hlfrun = 0.5* (b-a); result = 0.0; #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center + hlfrun*xg_leg[i]; f = pow(x,k)*sqrt(1.0+0.5*x*theta)/(1.0+exp(x-eta)); result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<num;i++) { x = center - hlfrun*xg_leg[i]; f = pow(x,k)*sqrt(1.0+0.5*x*theta)/(1.0+exp(x-eta)); result += f*wg_leg[i]; } res3 = result * hlfrun; const double xg_lag[10] = { 1.37793470540492430830772505652711188e-1, 7.29454549503170498160373121676078781e-1 , 1.80834290174031604823292007575060883e0 , 3.40143369785489951448253222140839067e0 , 5.55249614006380363241755848686876285e0 , 8.33015274676449670023876719727452218e0 , 1.18437858379000655649185389191416139e1 , 1.62792578313781020995326539358336223e1 , 2.19965858119807619512770901955944939e1 , 2.99206970122738915599087933407991951e1 }; const double wg_lag[10] = {3.54009738606996308762226891442067608e-1, 8.31902301043580738109829658127849577e-1 , 1.33028856174932817875279219439399369e0 , 1.86306390311113098976398873548246693e0 , 2.45025555808301016607269373165752256e0 , 3.12276415513518249615081826331455472e0 , 3.93415269556152109865581245924823077e0 , 4.99241487219302310201148565243315445e0 , 6.57220248513080297518766871037611234e0 , 9.78469584037463069477008663871859813e0 }; //integral 4 of 4: int_s3^\inf f(x) dx a=s3; b=1.0; result = 0.0; #pragma omp simd for(i=0;i<10;i++) { x = a+b*xg_lag[i]; f = pow(x,k)*sqrt(1.0+0.5*x*theta)/(1.0+exp(x-eta)); result += f*wg_lag[i]; } res4 = result*b; #if DEBUG printf("gaussFfermi: %.18e %.18e %.18e %.18e\n",res1,res2,res3,res4); #endif return res1+res2+res3+res4; } float gaussFfermif(const float k, const float eta, const float theta) { const float xg_leg[5] = {1.48874338981631210884826001129719984e-1f, 4.33395394129247190799265943165784162e-1f, 6.79409568299024406234327365114873575e-1f, 8.65063366688984510732096688423493048e-1f, 9.73906528517171720077964012084452053e-1f }; const float wg_leg[5] = {2.95524224714752870173892994651338329e-1f, 2.69266719309996355091226921569469352e-1f, 2.19086362515982043995534934228163192e-1f, 1.49451349150580593145776339657697332e-1f, 6.66713443086881375935688098933317928e-2f }; const float d = 3.3609e0 ; const float sg = 9.1186e-2 ; const float a1 = 6.7774e0 ; const float b1 = 1.1418e0 ; const float c1 = 2.9826e0 ; const float a2 = 3.7601e0 ; const float b2 = 9.3719e-2 ; const float c2 = 2.1063e-2 ; const float d2 = 3.1084e1 ; const float e2 = 1.0056e0 ; const float a3 = 7.5669e0 ; const float b3 = 1.1695e0 ; const float c3 = 7.5416e-1 ; const float d3 = 6.6558e0 ; const float e3 =-1.2819e-1 ; float x1,x2,x3,s1,s2,s3,s12,xi,xi2,eta1; float fd, res1,res2,res3,res4; // definition of xi: eta1=sg*(eta-d); if (eta1<50.0f) xi=logf(1.0f+expf(eta1))/sg; else xi=eta-d; xi2=xi*xi; // definition of the x_i: x1=(a1 +b1*xi+c1* xi2)/(1.0f+c1*xi); x2=(a2 +b2*xi+c2*d2*xi2)/(1.0f+e2*xi+c2* xi2); x3=(a3 +b3*xi+c3*d3*xi2)/(1.0f+e3*xi+c3* xi2); // breakpoints: s1=x1-x2; s2=x1; s3=x1+x3; s12=sqrtf(s1); //first integral of four: int_0^Sqrt[s1] f(x^2) 2x dx float center, hlfrun, result, x, z, f, a, b; int i; a=0.0f; b=s12; center = 0.5f* (a+b); hlfrun = 0.5f* (b-a); result = 0.0f; #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center + hlfrun*xg_leg[i]; z = x*x; f = powf(z,k)*sqrtf(1.0f+0.5f*z*theta)/(1.0f+expf(z-eta))*2.0f*x; result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center - hlfrun*xg_leg[i]; z = x*x; f = powf(z,k)*sqrtf(1.0f+0.5f*z*theta)/(1.0f+expf(z-eta))*2.0f*x; result += f*wg_leg[i]; } res1 = result * hlfrun; //integral 2 of 4: int_s1^s3 f(x) dx a=s1; b=s2; center = 0.5f* (a+b); hlfrun = 0.5f* (b-a); result = 0.0f; #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center + hlfrun*xg_leg[i]; f = powf(x,k)*sqrtf(1.0f+0.5f*x*theta)/(1.0f+expf(x-eta)); result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center - hlfrun*xg_leg[i]; f = powf(x,k)*sqrtf(1.0f+0.5f*x*theta)/(1.0f+expf(x-eta)); result += f*wg_leg[i]; } res2 = result * hlfrun; //integral 3 of 4: int_s2^s3 f(x) dx a=s2; b=s3; center = 0.5f* (a+b); hlfrun = 0.5f* (b-a); result = 0.0f; #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center + hlfrun*xg_leg[i]; f = powf(x,k)*sqrtf(1.0f+0.5f*x*theta)/(1.0f+expf(x-eta)); result += f*wg_leg[i]; } #pragma omp simd #pragma ivdep for(i=0;i<5;i++) { x = center - hlfrun*xg_leg[i]; f = powf(x,k)*sqrtf(1.0f+0.5f*x*theta)/(1.0f+expf(x-eta)); result += f*wg_leg[i]; } res3 = result * hlfrun; const float xg_lag[10] = { 1.37793470540492430830772505652711188e-1f, 7.29454549503170498160373121676078781e-1f , 1.80834290174031604823292007575060883e0f , 3.40143369785489951448253222140839067e0f , 5.55249614006380363241755848686876285e0f , 8.33015274676449670023876719727452218e0f , 1.18437858379000655649185389191416139e1f , 1.62792578313781020995326539358336223e1f , 2.19965858119807619512770901955944939e1f , 2.99206970122738915599087933407991951e1f }; const float wg_lag[10] = {3.54009738606996308762226891442067608e-1f, 8.31902301043580738109829658127849577e-1f , 1.33028856174932817875279219439399369e0f , 1.86306390311113098976398873548246693e0f , 2.45025555808301016607269373165752256e0f , 3.12276415513518249615081826331455472e0f , 3.93415269556152109865581245924823077e0f , 4.99241487219302310201148565243315445e0f , 6.57220248513080297518766871037611234e0f , 9.78469584037463069477008663871859813e0f }; result = 0.0f; a=s3; b=1.0f; #pragma omp simd for(i=0;i<10;i++) { x = a+b*xg_lag[i]; f = powf(x,k)*sqrtf(1.0f+0.5f*x*theta)/(1.0f+expf(x-eta)); result += f*wg_lag[i]; } res4 = result*b; return res1+res2+res3+res4; } double quickFfermi0(const double k, const double eta, const double theta) { int ii; double t, x, dx, integral=0.0; #include "tbl_double.h" t=-4.0; #pragma omp simd #pragma ivdep for(ii=0;ii<num;ii++) { x = exp(t-exp(-t)); dx = 1.0 +exp(-t); integral+= 1.0/(1.0+exp(x)*exp(-eta) ) *exp( (k+1.0) * (t - exp(-t)) ) *sqrt(1.0+ 0.5*theta*x) * dx; ; t+=h; } return h*integral; } double quickFfermi1(const double k, const double eta, const double theta) { //tabulated abcissas from Mathematica // we can also tabulate tTBL[ii] - exp(-tTBL[ii]) and exp(xTBL[ii]) #include "tbl_double.h" const double minus_exp_eta=exp(-eta); const double k_plus_1 = k+1.0; double integral = 0.0; int ii; //#pragma omp simd for(ii=0;ii<num;ii++) { integral+= 1.0/(1.0+exp(xTBL[ii])*minus_exp_eta ) *exp( (k_plus_1) * (tTBL[ii] - exp(-tTBL[ii])) ) *sqrt(1.0 + 0.5*theta*xTBL[ii]) * dxTBL[ii]; } return h*integral; } double quickFfermi2(const double k, const double eta, const double theta) { //tabulated abcissas from Mathematica #include "tbl_double.h" const double minus_exp_eta=exp(-eta); const double k_plus_1 = k+1.0; const double half_theta = 0.5*theta; double integral = 0.0; int ii; #pragma omp simd #pragma vector aligned #pragma ivdep for(ii=0;ii<num;ii++) { integral+= 1.0/(1.0+ExpxTBL[ii]*minus_exp_eta ) *exp( k_plus_1 * tExpTBL[ii] ) *sqrt(1.0 + half_theta*xTBL[ii]) * dxTBL[ii]; ; } return h*integral; } double quickFfermi3(const double k_dbl, const double eta_dbl, const double theta_dbl) { //tabulated abcissas from Mathematica #include "tbl_float.h" float k,eta,theta; float integral = 0.0f; int ii; k = (float) k_dbl; theta = (float) theta_dbl; eta = (float) eta_dbl; #pragma omp simd #pragma vector aligned #pragma ivdep for(ii=0;ii<num;ii++) { integral+= 1.0f/(1.0f+ExpxTBL[ii]*expf(-eta) ) *expf( (k+1.0f) * tExpTBL[ii] ) *sqrtf(1.0f + 0.5f*theta*xTBL[ii]) * dxTBL[ii]; ; } return (double) h*integral; }
GB_unop__atan_fc64_fc64.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__atan_fc64_fc64) // op(A') function: GB (_unop_tran__atan_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = catan (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_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 = catan (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = catan (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_ATAN || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__atan_fc64_fc64) ( GxB_FC64_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 ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catan (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 ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = catan (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__atan_fc64_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
trmv_x_csc_u_hi.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t trmv_csc_u_hi_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *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(); ALPHA_INT partition[thread_num + 1]; balanced_partition_row_by_nnz(A->cols_end, n, thread_num, partition); ALPHA_Number** tmp = (ALPHA_Number**)malloc(sizeof(ALPHA_Number*) * thread_num); #ifdef _OPENMP #pragma omp parallel num_threads(thread_num) #endif { const ALPHA_INT tid = alpha_get_thread_id(); const ALPHA_INT local_n_s = partition[tid]; const ALPHA_INT local_n_e = partition[tid + 1]; tmp[tid] = (ALPHA_Number*)malloc(sizeof(ALPHA_Number) * m); for(ALPHA_INT j = 0; j < m; ++j) { alpha_setzero(tmp[tid][j]); } for(ALPHA_INT i = local_n_s; i < local_n_e; ++i) { const ALPHA_Number x_r = x[i]; register ALPHA_Number tmp_t; alpha_setzero(tmp_t); ALPHA_INT cs = A->cols_start[i]; ALPHA_INT ce = A->cols_end[i]; for(; cs < ce-3; cs += 4) { const ALPHA_INT row_0 = A->row_indx[cs]; const ALPHA_INT row_1 = A->row_indx[cs+1]; const ALPHA_INT row_2 = A->row_indx[cs+2]; const ALPHA_INT row_3 = A->row_indx[cs+3]; if(row_3 < i) { alpha_mul(tmp_t, A->values[cs], x_r); alpha_madde(tmp[tid][row_0], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+1], x_r); alpha_madde(tmp[tid][row_1], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+2], x_r); alpha_madde(tmp[tid][row_2], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+3], x_r); alpha_madde(tmp[tid][row_3], alpha, tmp_t); }else if (row_2 < i){ alpha_mul(tmp_t, A->values[cs], x_r); alpha_madde(tmp[tid][row_0], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+1], x_r); alpha_madde(tmp[tid][row_1], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+2], x_r); alpha_madde(tmp[tid][row_2], alpha, tmp_t); }else if (row_1 < i){ alpha_mul(tmp_t, A->values[cs], x_r); alpha_madde(tmp[tid][row_0], alpha, tmp_t); alpha_mul(tmp_t, A->values[cs+1], x_r); alpha_madde(tmp[tid][row_1], alpha, tmp_t); }else if (row_0 < i){ alpha_mul(tmp_t, A->values[cs], x_r); alpha_madde(tmp[tid][row_0], alpha, tmp_t); } } for (;cs < ce;++cs) { const ALPHA_INT row = A->row_indx[cs]; if (row < i){ alpha_mul(tmp_t, A->values[cs], x_r); alpha_madde(tmp[tid][row], alpha, tmp_t); } } } } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { ALPHA_Number tmp_y; alpha_setzero(tmp_y); for(ALPHA_INT j = 0; j < thread_num; ++j) { alpha_add(tmp_y, tmp_y, tmp[j][i]); } alpha_madde(tmp_y, alpha, x[i]); alpha_madde(tmp_y, y[i], beta); y[i] = tmp_y; } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < thread_num; ++i) { free(tmp[i]); } free(tmp); return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_CSC *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return trmv_csc_u_hi_omp(alpha, A, x, beta, y); }
gbdt.h
#ifndef LIGHTGBM_BOOSTING_GBDT_H_ #define LIGHTGBM_BOOSTING_GBDT_H_ #include <LightGBM/boosting.h> #include <LightGBM/objective_function.h> #include <LightGBM/prediction_early_stop.h> #include <LightGBM/json11.hpp> #include "score_updater.hpp" #include <cstdio> #include <vector> #include <string> #include <fstream> #include <memory> #include <mutex> #include <map> using namespace json11; namespace LightGBM { /*! * \brief GBDT algorithm implementation. including Training, prediction, bagging. */ class GBDT : public GBDTBase { public: /*! * \brief Constructor */ GBDT(); /*! * \brief Destructor */ ~GBDT(); /*! * \brief Initialization logic * \param gbdt_config Config for boosting * \param train_data Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void Init(const Config* gbdt_config, const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Merge model from other boosting object. Will insert to the front of current boosting object * \param other */ void MergeFrom(const Boosting* other) override { auto other_gbdt = reinterpret_cast<const GBDT*>(other); // tmp move to other vector auto original_models = std::move(models_); models_ = std::vector<std::unique_ptr<Tree>>(); // push model from other first for (const auto& tree : other_gbdt->models_) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_init_iteration_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; // push model in current object for (const auto& tree : original_models) { auto new_tree = std::unique_ptr<Tree>(new Tree(*(tree.get()))); models_.push_back(std::move(new_tree)); } num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; } void ShuffleModels(int start_iter, int end_iter) override { int total_iter = static_cast<int>(models_.size()) / num_tree_per_iteration_; start_iter = std::max(0, start_iter); if (end_iter <= 0) { end_iter = total_iter; } end_iter = std::min(total_iter, end_iter); auto original_models = std::move(models_); std::vector<int> indices(total_iter); for (int i = 0; i < total_iter; ++i) { indices[i] = i; } Random tmp_rand(17); for (int i = start_iter; i < end_iter - 1; ++i) { int j = tmp_rand.NextShort(i + 1, end_iter); std::swap(indices[i], indices[j]); } models_ = std::vector<std::unique_ptr<Tree>>(); for (int i = 0; i < total_iter; ++i) { for (int j = 0; j < num_tree_per_iteration_; ++j) { int tree_idx = indices[i] * num_tree_per_iteration_ + j; auto new_tree = std::unique_ptr<Tree>(new Tree(*(original_models[tree_idx].get()))); models_.push_back(std::move(new_tree)); } } } /*! * \brief Reset the training data * \param train_data New Training data * \param objective_function Training objective function * \param training_metrics Training metrics */ void ResetTrainingData(const Dataset* train_data, const ObjectiveFunction* objective_function, const std::vector<const Metric*>& training_metrics) override; /*! * \brief Reset Boosting Config * \param gbdt_config Config for boosting */ void ResetConfig(const Config* gbdt_config) override; void SetSplitCallback(SplitCallback* callback) override { tree_learner_->SetSplitCallback(callback); } void SetCategoricalSplitCallback(CategoricalSplitCallback* callback) override { tree_learner_->SetCategoricalSplitCallback(callback); } /*! * \brief Adding a validation dataset * \param valid_data Validation dataset * \param valid_metrics Metrics for validation dataset */ void AddValidDataset(const Dataset* valid_data, const std::vector<const Metric*>& valid_metrics) override; /*! * \brief Perform a full training procedure * \param snapshot_freq frequence of snapshot * \param model_output_path path of model file */ void Train(int snapshot_freq, const std::string& model_output_path) override; void RefitTree(const std::vector<std::vector<int>>& tree_leaf_prediction) override; /*! * \brief Training logic * \param gradients nullptr for using default objective, otherwise use self-defined boosting * \param hessians nullptr for using default objective, otherwise use self-defined boosting * \return True if cannot train any more */ virtual bool TrainOneIter(const score_t* gradients, const score_t* hessians) override; /*! * \brief Rollback one iteration */ void RollbackOneIter() override; /*! * \brief Get current iteration */ int GetCurrentIteration() const override { return static_cast<int>(models_.size()) / num_tree_per_iteration_; } /*! * \brief Can use early stopping for prediction or not * \return True if cannot use early stopping for prediction */ bool NeedAccuratePrediction() const override { if (objective_function_ == nullptr) { return true; } else { return objective_function_->NeedAccuratePrediction(); } } /*! * \brief Get evaluation result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return evaluation result */ std::vector<double> GetEvalAt(int data_idx) const override; /*! * \brief Get current training score * \param out_len length of returned score * \return training score */ virtual const double* GetTrainingScore(int64_t* out_len) override; /*! * \brief Get size of prediction at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \return The size of prediction */ virtual int64_t GetNumPredictAt(int data_idx) const override { CHECK(data_idx >= 0 && data_idx <= static_cast<int>(valid_score_updater_.size())); data_size_t num_data = train_data_->num_data(); if (data_idx > 0) { num_data = valid_score_updater_[data_idx - 1]->num_data(); } return num_data * num_class_; } /*! * \brief Get prediction result at data_idx data * \param data_idx 0: training data, 1: 1st validation data * \param result used to store prediction result, should allocate memory before call this function * \param out_len length of returned score */ void GetPredictAt(int data_idx, double* out_result, int64_t* out_len) override; /*! * \brief Get number of prediction for one data * \param num_iteration number of used iterations * \param is_pred_leaf True if predicting leaf index * \param is_pred_contrib True if predicting feature contribution * \return number of prediction */ inline int NumPredictOneRow(int num_iteration, bool is_pred_leaf, bool is_pred_contrib) const override { int num_preb_in_one_row = num_class_; if (is_pred_leaf) { int max_iteration = GetCurrentIteration(); if (num_iteration > 0) { num_preb_in_one_row *= static_cast<int>(std::min(max_iteration, num_iteration)); } else { num_preb_in_one_row *= max_iteration; } } else if (is_pred_contrib) { num_preb_in_one_row = num_tree_per_iteration_ * (max_feature_idx_ + 2); // +1 for 0-based indexing, +1 for baseline } return num_preb_in_one_row; } void PredictRaw(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictRawByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void Predict(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; void PredictByMap(const std::unordered_map<int, double>& features, double* output, const PredictionEarlyStopInstance* early_stop) const override; void PredictLeafIndex(const double* features, double* output) const override; void PredictLeafIndexByMap(const std::unordered_map<int, double>& features, double* output) const override; void PredictContrib(const double* features, double* output, const PredictionEarlyStopInstance* earlyStop) const override; /*! * \brief Dump model to json format string * \param start_iteration The model will be saved start from * \param num_iteration Number of iterations that want to dump, -1 means dump all * \return Json format string of model */ std::string DumpModel(int start_iteration, int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \return if-else format codes of model */ std::string ModelToIfElse(int num_iteration) const override; /*! * \brief Translate model to if-else statement * \param num_iteration Number of iterations that want to translate, -1 means translate all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ bool SaveModelToIfElse(int num_iteration, const char* filename) const override; /*! * \brief Save model to file * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \param filename Filename that want to save to * \return is_finish Is training finished or not */ virtual bool SaveModelToFile(int start_iteration, int num_iterations, const char* filename) const override; /*! * \brief Save model to string * \param start_iteration The model will be saved start from * \param num_iterations Number of model that want to save, -1 means save all * \return Non-empty string if succeeded */ virtual std::string SaveModelToString(int start_iteration, int num_iterations) const override; /*! * \brief Restore from a serialized buffer */ bool LoadModelFromString(const char* buffer, size_t len) override; /*! * \brief Calculate feature importances * \param num_iteration Number of model that want to use for feature importance, -1 means use all * \param importance_type: 0 for split, 1 for gain * \return vector of feature_importance */ std::vector<double> FeatureImportance(int num_iteration, int importance_type) const override; /*! * \brief Get max feature index of this model * \return Max feature index of this model */ inline int MaxFeatureIdx() const override { return max_feature_idx_; } /*! * \brief Get feature names of this model * \return Feature names of this model */ inline std::vector<std::string> FeatureNames() const override { return feature_names_; } /*! * \brief Get index of label column * \return index of label column */ inline int LabelIdx() const override { return label_idx_; } /*! * \brief Get number of weak sub-models * \return Number of weak sub-models */ inline int NumberOfTotalModel() const override { return static_cast<int>(models_.size()); } /*! * \brief Get number of tree per iteration * \return number of tree per iteration */ inline int NumModelPerIteration() const override { return num_tree_per_iteration_; } /*! * \brief Get number of classes * \return Number of classes */ inline int NumberOfClasses() const override { return num_class_; } inline void InitPredict(int num_iteration, bool is_pred_contrib) override { num_iteration_for_pred_ = static_cast<int>(models_.size()) / num_tree_per_iteration_; if (num_iteration > 0) { num_iteration_for_pred_ = std::min(num_iteration, num_iteration_for_pred_); } if (is_pred_contrib) { #pragma omp parallel for schedule(static) for (int i = 0; i < static_cast<int>(models_.size()); ++i) { models_[i]->RecomputeMaxDepth(); } } } inline double GetLeafValue(int tree_idx, int leaf_idx) const override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); return models_[tree_idx]->LeafOutput(leaf_idx); } inline void SetLeafValue(int tree_idx, int leaf_idx, double val) override { CHECK(tree_idx >= 0 && static_cast<size_t>(tree_idx) < models_.size()); CHECK(leaf_idx >= 0 && leaf_idx < models_[tree_idx]->num_leaves()); models_[tree_idx]->SetLeafOutput(leaf_idx, val); } /*! * \brief Get Type name of this boosting object */ virtual const char* SubModelName() const override { return "tree"; } protected: /*! * \brief Print eval result and check early stopping */ virtual bool EvalAndCheckEarlyStopping(); /*! * \brief reset config for bagging */ void ResetBaggingConfig(const Config* config, bool is_change_dataset); /*! * \brief Implement bagging logic * \param iter Current interation */ virtual void Bagging(int iter); /*! * \brief Helper function for bagging, used for multi-threading optimization * \param start start indice of bagging * \param cnt count * \param buffer output buffer * \return count of left size */ data_size_t BaggingHelper(Random& cur_rand, data_size_t start, data_size_t cnt, data_size_t* buffer); /*! * \brief calculate the object function */ virtual void Boosting(); /*! * \brief updating score after tree was trained * \param tree Trained tree of this iteration * \param cur_tree_id Current tree for multiclass training */ virtual void UpdateScore(const Tree* tree, const int cur_tree_id); /*! * \brief eval results for one metric */ virtual std::vector<double> EvalOneMetric(const Metric* metric, const double* score) const; /*! * \brief Print metric result of current iteration * \param iter Current interation * \return best_msg if met early_stopping */ std::string OutputMetric(int iter); double BoostFromAverage(int class_id, bool update_scorer); /*! \brief current iteration */ int iter_; /*! \brief Pointer to training data */ const Dataset* train_data_; /*! \brief Config of gbdt */ std::unique_ptr<Config> config_; /*! \brief Tree learner, will use this class to learn trees */ std::unique_ptr<TreeLearner> tree_learner_; /*! \brief Objective function */ const ObjectiveFunction* objective_function_; /*! \brief Store and update training data's score */ std::unique_ptr<ScoreUpdater> train_score_updater_; /*! \brief Metrics for training data */ std::vector<const Metric*> training_metrics_; /*! \brief Store and update validation data's scores */ std::vector<std::unique_ptr<ScoreUpdater>> valid_score_updater_; /*! \brief Metric for validation data */ std::vector<std::vector<const Metric*>> valid_metrics_; /*! \brief Number of rounds for early stopping */ int early_stopping_round_; /*! \brief Best iteration(s) for early stopping */ std::vector<std::vector<int>> best_iter_; /*! \brief Best score(s) for early stopping */ std::vector<std::vector<double>> best_score_; /*! \brief output message of best iteration */ std::vector<std::vector<std::string>> best_msg_; /*! \brief Trained models(trees) */ std::vector<std::unique_ptr<Tree>> models_; /*! \brief Max feature index of training data*/ int max_feature_idx_; /*! \brief First order derivative of training data */ std::vector<score_t> gradients_; /*! \brief Secend order derivative of training data */ std::vector<score_t> hessians_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t> bag_data_indices_; /*! \brief Number of in-bag data */ data_size_t bag_data_cnt_; /*! \brief Store the indices of in-bag data */ std::vector<data_size_t> tmp_indices_; /*! \brief Number of training data */ data_size_t num_data_; /*! \brief Number of trees per iterations */ int num_tree_per_iteration_; /*! \brief Number of class */ int num_class_; /*! \brief Index of label column */ data_size_t label_idx_; /*! \brief number of used model */ int num_iteration_for_pred_; /*! \brief Shrinkage rate for one iteration */ double shrinkage_rate_; /*! \brief Number of loaded initial models */ int num_init_iteration_; /*! \brief Feature names */ std::vector<std::string> feature_names_; std::vector<std::string> feature_infos_; /*! \brief number of threads */ int num_threads_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> offsets_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_cnts_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> left_write_pos_buf_; /*! \brief Buffer for multi-threading bagging */ std::vector<data_size_t> right_write_pos_buf_; std::unique_ptr<Dataset> tmp_subset_; bool is_use_subset_; std::vector<bool> class_need_train_; bool is_constant_hessian_; std::unique_ptr<ObjectiveFunction> loaded_objective_; bool average_output_; bool need_re_bagging_; std::string loaded_parameter_; Json forced_splits_json_; }; } // namespace LightGBM #endif // LightGBM_BOOSTING_GBDT_H_
matmul.c
/* * In His Exalted Name * Title: Matrix Multiplication Sequential Code * Author: Ahmad Siavashi, Email: siavashi@aut.ac.ir * Date: 15/11/2015 */ /* * Parallelization: Ali Gholami */ // Let it be. #define _CRT_SECURE_NO_WARNINGS #define NUM_THREADS 8 // Global variable to check the summation of the elements of the result long long int CHECK_SUM = 0; #include <stdlib.h> #include <stdio.h> #include <time.h> #include <omp.h> typedef struct { int *A, *B, *C, *C_PRIME; int n, m, p; } DataSet; void fillDataSet(DataSet *dataSet); void printDataSet(DataSet dataSet); void closeDataSet(DataSet dataSet); void multiply(DataSet dataSet); void multiply_parallel(DataSet dataset); int main(int argc, char *argv[]){ DataSet dataSet; if(argc < 4){ printf("[-] Invalid No. of arguments.\n"); printf("[-] Try -> <n> <m> <p>\n"); printf(">>> "); scanf("%d %d %d", &dataSet.n, &dataSet.m, &dataSet.p); }else{ dataSet.n = atoi(argv[1]); dataSet.m = atoi(argv[2]); dataSet.p = atoi(argv[3]); } // Get the current time float start_time, elapsed_time; // Repeat the process 6 times int i = 0; for(i = 0; i < 6; i++) { fillDataSet(&dataSet); // Do the parallel first without considering the time multiply(dataSet); CHECK_SUM = 0; omp_set_num_threads(NUM_THREADS); start_time = omp_get_wtime(); multiply_parallel(dataSet); elapsed_time += omp_get_wtime() - start_time; // printDataSet(dataSet); // Calculate the check sum int cmp = memcmp(dataSet.C, dataSet.C_PRIME, dataSet.n * dataSet.p); // if cmp == 0 we are good to go :-) printf("\nIteration [%d] Compare Results: %d\n", i, cmp); closeDataSet(dataSet); } // report elapsed time printf("\nAverage Time Elapsed %lf Secs\n", elapsed_time/6 * 10); system("PAUSE"); return EXIT_SUCCESS; } void fillDataSet(DataSet *dataSet){ int i, j; dataSet->A = (int *) malloc(sizeof(int) * dataSet->n * dataSet->m); dataSet->B = (int *) malloc(sizeof(int) * dataSet->m * dataSet->p); dataSet->C = (int *) malloc(sizeof(int) * dataSet->n * dataSet->p); dataSet->C_PRIME = (int *) malloc(sizeof(int) * dataSet->n * dataSet->p); srand(1); for(i = 0; i < dataSet->n; i++){ for(j = 0; j < dataSet->m; j++){ dataSet->A[i*dataSet->m + j] = rand() % 100; } } for(i = 0; i < dataSet->m; i++){ for(j = 0; j < dataSet->p; j++){ dataSet->B[i*dataSet->p + j] = rand() % 100; } } } void printDataSet(DataSet dataSet){ int i, j; printf("[-] Matrix A\n"); for(i = 0; i < dataSet.n; i++){ for(j = 0; j < dataSet.m; j++){ printf("%-4d", dataSet.A[i*dataSet.m + j]); } putchar('\n'); } printf("[-] Matrix B\n"); for(i = 0; i < dataSet.m; i++){ for(j = 0; j < dataSet.p; j++){ printf("%-4d", dataSet.B[i*dataSet.p + j]); } putchar('\n'); } printf("[-] Matrix C\n"); for(i = 0; i < dataSet.n; i++){ for(j = 0; j < dataSet.p; j++){ printf("%-8d", dataSet.C[i*dataSet.p + j]); } putchar('\n'); } } void closeDataSet(DataSet dataSet){ free(dataSet.A); free(dataSet.B); free(dataSet.C); free(dataSet.C_PRIME); } // Serial void multiply(DataSet dataSet) { int i, j, k, sum; for (i = 0; i < dataSet.n; i++) { for (j = 0; j < dataSet.p; j++) { sum = 0; for (k = 0; k < dataSet.m; k++) { sum += dataSet.A[i * dataSet.m + k] * dataSet.B[k * dataSet.p + j]; } dataSet.C_PRIME[i * dataSet.p + j] = sum; } } } void multiply_parallel(DataSet dataSet){ int i, j, k, sum; #pragma omp parallel for schedule(dynamic, 200) for(i = 0; i < dataSet.n; i++){ #pragma omp parallel for schedule(dynamic, 200) for(j = 0; j < dataSet.p; j++){ sum = 0; for(k = 0; k < dataSet.m; k++){ sum += dataSet.A[i * dataSet.m + k] * dataSet.B[k * dataSet.p + j]; } dataSet.C[i * dataSet.p + j] = sum; } } }
error.h
#include <math.h> #include "disptools.h" /*! * \brief Redistribute the volume change over the image. * * Redistribute the change of volume within the body on the background, * and enforce the total volume change over the entire image to be zero. */ static inline void redistribute_volume_change( const Image J, const Mask mask ) { FLOATING total_change = 0.0; size_t background_voxels_count = 0; for (size_t z = 0; z < J.nz; ++z) { for (size_t y = 0; y < J.ny; ++y) { for (size_t x = 0; x < J.nx; ++x) { total_change += __(J, x, y, z) - 1.0; if (!__(mask, x, y, z)) { background_voxels_count += 1; } } } } const FLOATING correction = -total_change / background_voxels_count; for (size_t z = 0; z < J.nz; ++z) { for (size_t y = 0; y < J.ny; ++y) { for (size_t x = 0; x < J.nx; ++x) { if (!__(mask, x, y, z)) { __(J, x, y, z) = __(J, x, y, z) + correction; } } } } } /*! * \brief Compute a tolerance map over the volume. * * The tolerance is zero within the body volume and along the boundary, * while it is set to `tolerance' on the remaining background space. * Zero tolerance on the boundary prevents the vector field from * flowing outside the image space in the contours of the regions * where the body touches the boundary. * * \note: The resulting `Image' object must be deallocated with `destroy_image'. */ static inline Image create_tolerance_map( const Mask mask, const FLOATING tolerance ) { const size_t nx = mask.nx, ny = mask.ny, nz = mask.nz; Image tolerance_map = new_image(1, nx, ny, nz, 1.0, 1.0, 1.0); if (!tolerance_map.data) { return tolerance_map; } for (size_t z = 0; z < nz; ++z) { for (size_t y = 0; y < ny; ++y) { for (size_t x = 0; x < nx; ++x) { if (__(mask, x, y, z) || x == 0 || y == 0 || z == 0 || x == nx-1 || y == ny-1 || z == nz-1) { __(tolerance_map, x, y, z) = 0.0; } else { __(tolerance_map, x, y, z) = tolerance; } } } } return tolerance_map; } /*! * \brief Compute the error on the Jacobian of the moving field. */ static inline FLOATING compute_error( const Image J, /*!< Target Jacobian */ const Image J_field, /*!< Current Jacobian */ const Mask mask, /*!< Body mask */ const FLOATING tolerance, /*!< Jacobian tolerance on background */ const Image voxel_error, /*!< Error on the Jacobian */ FLOATING *max_voxel_error /*!< Maximum voxel error */ ) { // Cumulative error over the entire Jacobian map FLOATING total_error = 0.0; // Local variable for maximum voxel error FLOATING max_error = 0.0; // Compute the error on the Jacobian map for all voxels #ifdef __GNUC__ #define MAX_ERROR_ACC max_error #pragma omp parallel for \ reduction(+: total_error) \ reduction(max: max_error) \ collapse(3) \ schedule(static) for (size_t z = 0; z < J.nz; ++z) { for (size_t y = 0; y < J.ny; ++y) { for (size_t x = 0; x < J.nx; ++x) { #else // MSVC 15 does not support OpenMP > 2.0 #define MAX_ERROR_ACC local_max_error #pragma omp parallel { FLOATING local_max_error = 0.0; int z; #pragma omp for nowait \ reduction(+: total_error) for (z = 0; z < J.nz; ++z) { for (size_t y = 0; y < J.ny; ++y) { for (size_t x = 0; x < J.nx; ++x) { #endif // Compute the error on the voxel FLOATING error = __(J_field, x, y, z) - __(J, x, y, z); // Inside the body mask if (__(mask, x, y, z)) { __(voxel_error, x, y, z) = error; } // Tolerate some error in the background else { const FLOATING abs_error = fabs(error); __(voxel_error, x, y, z) = abs_error < tolerance ? 0.0 : copysign(abs_error - tolerance, error); } // Update total and maximum local errors // The maximum voxel error is checked only within the // body volume marked by the mask total_error += __(voxel_error, x, y, z) * __(voxel_error, x, y, z); if (__(mask, x, y, z) && fabs(__(voxel_error, x, y, z)) > MAX_ERROR_ACC) { MAX_ERROR_ACC = fabs(__(voxel_error, x, y, z)); } } } } #ifndef __GNUC__ // Manual max reduction, MSVC 15 does not provide it #pragma omp critical { if (local_max_error > max_error) { max_error = local_max_error; } } } // pragma omp parallel #endif #undef MAX_ERROR_ACC // Return maximum voxel error *max_voxel_error = max_error; return total_error; }
cancel-parallel-1.c
/* { dg-do run } */ /* { dg-set-target-env-var OMP_CANCELLATION "true" } */ #include <stdlib.h> #include <omp.h> int main () { #pragma omp parallel num_threads (32) { #pragma omp cancel parallel if (omp_get_cancellation ()) abort (); } return 0; }